TypeGuesserChain.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. protected $guessers = array();
  23. /**
  24. * @param array $guessers
  25. */
  26. public function __construct(array $guessers)
  27. {
  28. foreach ($guessers as $guesser) {
  29. if (!$guesser instanceof TypeGuesserInterface) {
  30. throw new UnexpectedTypeException($guesser, 'Sonata\AdminBundle\Guesser\TypeGuesserInterface');
  31. }
  32. if ($guesser instanceof self) {
  33. $this->guessers = array_merge($this->guessers, $guesser->guessers);
  34. } else {
  35. $this->guessers[] = $guesser;
  36. }
  37. }
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function guessType($class, $property, ModelManagerInterface $modelManager)
  43. {
  44. return $this->guess(function ($guesser) use ($class, $property, $modelManager) {
  45. return $guesser->guessType($class, $property, $modelManager);
  46. });
  47. }
  48. /**
  49. * Executes a closure for each guesser and returns the best guess from the
  50. * return values.
  51. *
  52. * @param \Closure $closure The closure to execute. Accepts a guesser
  53. * as argument and should return a Guess instance
  54. *
  55. * @return Guess The guess with the highest confidence
  56. */
  57. private function guess(\Closure $closure)
  58. {
  59. $guesses = array();
  60. foreach ($this->guessers as $guesser) {
  61. if ($guess = $closure($guesser)) {
  62. $guesses[] = $guess;
  63. }
  64. }
  65. return Guess::getBestGuess($guesses);
  66. }
  67. }