vendor/symfony/form/FormTypeGuesserChain.php line 91

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Form;
  11. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  12. use Symfony\Component\Form\Guess\Guess;
  13. class FormTypeGuesserChain implements FormTypeGuesserInterface
  14. {
  15. private $guessers = [];
  16. /**
  17. * @param FormTypeGuesserInterface[] $guessers
  18. *
  19. * @throws UnexpectedTypeException if any guesser does not implement FormTypeGuesserInterface
  20. */
  21. public function __construct(iterable $guessers)
  22. {
  23. $tmpGuessers = [];
  24. foreach ($guessers as $guesser) {
  25. if (!$guesser instanceof FormTypeGuesserInterface) {
  26. throw new UnexpectedTypeException($guesser, FormTypeGuesserInterface::class);
  27. }
  28. if ($guesser instanceof self) {
  29. $tmpGuessers[] = $guesser->guessers;
  30. } else {
  31. $tmpGuessers[] = [$guesser];
  32. }
  33. }
  34. $this->guessers = array_merge([], ...$tmpGuessers);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function guessType(string $class, string $property)
  40. {
  41. return $this->guess(function ($guesser) use ($class, $property) {
  42. return $guesser->guessType($class, $property);
  43. });
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function guessRequired(string $class, string $property)
  49. {
  50. return $this->guess(function ($guesser) use ($class, $property) {
  51. return $guesser->guessRequired($class, $property);
  52. });
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function guessMaxLength(string $class, string $property)
  58. {
  59. return $this->guess(function ($guesser) use ($class, $property) {
  60. return $guesser->guessMaxLength($class, $property);
  61. });
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function guessPattern(string $class, string $property)
  67. {
  68. return $this->guess(function ($guesser) use ($class, $property) {
  69. return $guesser->guessPattern($class, $property);
  70. });
  71. }
  72. /**
  73. * Executes a closure for each guesser and returns the best guess from the
  74. * return values.
  75. *
  76. * @param \Closure $closure The closure to execute. Accepts a guesser
  77. * as argument and should return a Guess instance
  78. */
  79. private function guess(\Closure $closure): ?Guess
  80. {
  81. $guesses = [];
  82. foreach ($this->guessers as $guesser) {
  83. if ($guess = $closure($guesser)) {
  84. $guesses[] = $guess;
  85. }
  86. }
  87. return Guess::getBestGuess($guesses);
  88. }
  89. }