ContainerConstraintValidatorFactory.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\Validator;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  13. use Symfony\Component\Validator\Exception\ValidatorException;
  14. /**
  15. * Uses a service container to create constraint validators.
  16. *
  17. * @author Kris Wallsmith <kris@symfony.com>
  18. */
  19. class ContainerConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
  20. {
  21. private $container;
  22. private $validators;
  23. public function __construct(ContainerInterface $container)
  24. {
  25. $this->container = $container;
  26. $this->validators = [];
  27. }
  28. /**
  29. * {@inheritdoc}
  30. *
  31. * @throws ValidatorException When the validator class does not exist
  32. * @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
  33. */
  34. public function getInstance(Constraint $constraint)
  35. {
  36. $name = $constraint->validatedBy();
  37. if (!isset($this->validators[$name])) {
  38. if ($this->container->has($name)) {
  39. $this->validators[$name] = $this->container->get($name);
  40. } else {
  41. if (!class_exists($name)) {
  42. throw new ValidatorException(sprintf('Constraint validator "%s" does not exist or is not enabled. Check the "validatedBy" method in your constraint class "%s".', $name, get_debug_type($constraint)));
  43. }
  44. $this->validators[$name] = new $name();
  45. }
  46. }
  47. if (!$this->validators[$name] instanceof ConstraintValidatorInterface) {
  48. throw new UnexpectedTypeException($this->validators[$name], ConstraintValidatorInterface::class);
  49. }
  50. return $this->validators[$name];
  51. }
  52. }