TypeGuesserChain.php 2.2 KB

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