Chris@14: Chris@14: * Chris@14: * For the full copyright and license information, please view the LICENSE Chris@14: * file that was distributed with this source code. Chris@14: */ Chris@14: Chris@14: namespace Symfony\Component\Validator; Chris@14: Chris@14: use Psr\Container\ContainerInterface; Chris@14: use Symfony\Component\Validator\Exception\UnexpectedTypeException; Chris@14: use Symfony\Component\Validator\Exception\ValidatorException; Chris@14: Chris@14: /** Chris@14: * Uses a service container to create constraint validators. Chris@14: * Chris@14: * @author Kris Wallsmith Chris@14: */ Chris@14: class ContainerConstraintValidatorFactory implements ConstraintValidatorFactoryInterface Chris@14: { Chris@14: private $container; Chris@14: private $validators; Chris@14: Chris@14: public function __construct(ContainerInterface $container) Chris@14: { Chris@14: $this->container = $container; Chris@17: $this->validators = []; Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: * Chris@14: * @throws ValidatorException When the validator class does not exist Chris@14: * @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface Chris@14: */ Chris@14: public function getInstance(Constraint $constraint) Chris@14: { Chris@14: $name = $constraint->validatedBy(); Chris@14: Chris@14: if (!isset($this->validators[$name])) { Chris@14: if ($this->container->has($name)) { Chris@14: $this->validators[$name] = $this->container->get($name); Chris@14: } else { Chris@14: if (!class_exists($name)) { Chris@17: 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_class($constraint))); Chris@14: } Chris@14: Chris@14: $this->validators[$name] = new $name(); Chris@14: } Chris@14: } Chris@14: Chris@14: if (!$this->validators[$name] instanceof ConstraintValidatorInterface) { Chris@14: throw new UnexpectedTypeException($this->validators[$name], ConstraintValidatorInterface::class); Chris@14: } Chris@14: Chris@14: return $this->validators[$name]; Chris@14: } Chris@14: }