4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator;
14 use Psr\Container\ContainerInterface;
15 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
16 use Symfony\Component\Validator\Exception\ValidatorException;
19 * Uses a service container to create constraint validators.
21 * @author Kris Wallsmith <kris@symfony.com>
23 class ContainerConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
28 public function __construct(ContainerInterface $container)
30 $this->container = $container;
31 $this->validators = array();
37 * @throws ValidatorException When the validator class does not exist
38 * @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
40 public function getInstance(Constraint $constraint)
42 $name = $constraint->validatedBy();
44 if (!isset($this->validators[$name])) {
45 if ($this->container->has($name)) {
46 $this->validators[$name] = $this->container->get($name);
48 if (!class_exists($name)) {
49 throw new ValidatorException(sprintf('Constraint validator "%s" does not exist or it is not enabled. Check the "validatedBy" method in your constraint class "%s".', $name, \get_class($constraint)));
52 $this->validators[$name] = new $name();
56 if (!$this->validators[$name] instanceof ConstraintValidatorInterface) {
57 throw new UnexpectedTypeException($this->validators[$name], ConstraintValidatorInterface::class);
60 return $this->validators[$name];