TypeGuesserChain.php 2.2 KB

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