TypeGuesserChain.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. *
  10. */
  11. namespace Sonata\AdminBundle\Guesser;
  12. use Sonata\AdminBundle\Guesser\TypeGuesserInterface;
  13. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Form\Guess\Guess;
  15. /**
  16. *
  17. * The code is based on Symfony2 Form Components
  18. *
  19. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  20. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  21. */
  22. class TypeGuesserChain implements TypeGuesserInterface
  23. {
  24. protected $guessers = array();
  25. public function __construct(array $guessers)
  26. {
  27. foreach ($guessers as $guesser) {
  28. if (!$guesser instanceof TypeGuesserInterface) {
  29. throw new UnexpectedTypeException($guesser, 'Sonata\AdminBundle\Guesser\TypeGuesserInterface');
  30. }
  31. if ($guesser instanceof self) {
  32. $this->guessers = array_merge($this->guessers, $guesser->guessers);
  33. } else {
  34. $this->guessers[] = $guesser;
  35. }
  36. }
  37. }
  38. /**
  39. * @param $class
  40. * @param $property
  41. * @return FieldFactoryGuess
  42. */
  43. public function guessType($class, $property)
  44. {
  45. return $this->guess(function ($guesser) use ($class, $property) {
  46. return $guesser->guessType($class, $property);
  47. });
  48. }
  49. /**
  50. * Executes a closure for each guesser and returns the best guess from the
  51. * return values
  52. *
  53. * @param \Closure $closure The closure to execute. Accepts a guesser
  54. * as argument and should return a Guess instance
  55. *
  56. * @return FieldFactoryGuess The guess with the highest confidence
  57. */
  58. private function guess(\Closure $closure)
  59. {
  60. $guesses = array();
  61. foreach ($this->guessers as $guesser) {
  62. if ($guess = $closure($guesser)) {
  63. $guesses[] = $guess;
  64. }
  65. }
  66. return Guess::getBestGuess($guesses);
  67. }
  68. }