annotate vendor/symfony/validator/ContainerConstraintValidatorFactory.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 129ea1e6d783
children
rev   line source
Chris@14 1 <?php
Chris@14 2
Chris@14 3 /*
Chris@14 4 * This file is part of the Symfony package.
Chris@14 5 *
Chris@14 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@14 7 *
Chris@14 8 * For the full copyright and license information, please view the LICENSE
Chris@14 9 * file that was distributed with this source code.
Chris@14 10 */
Chris@14 11
Chris@14 12 namespace Symfony\Component\Validator;
Chris@14 13
Chris@14 14 use Psr\Container\ContainerInterface;
Chris@14 15 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
Chris@14 16 use Symfony\Component\Validator\Exception\ValidatorException;
Chris@14 17
Chris@14 18 /**
Chris@14 19 * Uses a service container to create constraint validators.
Chris@14 20 *
Chris@14 21 * @author Kris Wallsmith <kris@symfony.com>
Chris@14 22 */
Chris@14 23 class ContainerConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
Chris@14 24 {
Chris@14 25 private $container;
Chris@14 26 private $validators;
Chris@14 27
Chris@14 28 public function __construct(ContainerInterface $container)
Chris@14 29 {
Chris@14 30 $this->container = $container;
Chris@17 31 $this->validators = [];
Chris@14 32 }
Chris@14 33
Chris@14 34 /**
Chris@14 35 * {@inheritdoc}
Chris@14 36 *
Chris@14 37 * @throws ValidatorException When the validator class does not exist
Chris@14 38 * @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
Chris@14 39 */
Chris@14 40 public function getInstance(Constraint $constraint)
Chris@14 41 {
Chris@14 42 $name = $constraint->validatedBy();
Chris@14 43
Chris@14 44 if (!isset($this->validators[$name])) {
Chris@14 45 if ($this->container->has($name)) {
Chris@14 46 $this->validators[$name] = $this->container->get($name);
Chris@14 47 } else {
Chris@14 48 if (!class_exists($name)) {
Chris@17 49 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 50 }
Chris@14 51
Chris@14 52 $this->validators[$name] = new $name();
Chris@14 53 }
Chris@14 54 }
Chris@14 55
Chris@14 56 if (!$this->validators[$name] instanceof ConstraintValidatorInterface) {
Chris@14 57 throw new UnexpectedTypeException($this->validators[$name], ConstraintValidatorInterface::class);
Chris@14 58 }
Chris@14 59
Chris@14 60 return $this->validators[$name];
Chris@14 61 }
Chris@14 62 }