added friendly exception when constraint validator does not exist or it is not enabled

This commit is contained in:
Yonel Ceruto 2016-08-12 08:09:39 -04:00 committed by Fabien Potencier
parent 384995e6da
commit b66ea5e16e
2 changed files with 21 additions and 0 deletions

View File

@ -62,4 +62,19 @@ class ConstraintValidatorFactoryTest extends \PHPUnit_Framework_TestCase
$factory = new ConstraintValidatorFactory($container, array('validator_constraint_alias' => 'validator_constraint_service'));
$this->assertSame($validator, $factory->getInstance($constraint));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ValidatorException
*/
public function testGetInstanceInvalidValidatorClass()
{
$constraint = $this->getMock('Symfony\\Component\\Validator\\Constraint');
$constraint
->expects($this->once())
->method('validatedBy')
->will($this->returnValue('Fully\\Qualified\\ConstraintValidator\\Class\\Name'));
$factory = new ConstraintValidatorFactory(new Container());
$factory->getInstance($constraint);
}
}

View File

@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidatorFactoryInterface;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
@ -61,6 +62,7 @@ class ConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
*
* @return ConstraintValidatorInterface A validator for the supplied constraint
*
* @throws ValidatorException When the validator class does not exist
* @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
*/
public function getInstance(Constraint $constraint)
@ -68,6 +70,10 @@ class ConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
$name = $constraint->validatedBy();
if (!isset($this->validators[$name])) {
if (!class_exists($name)) {
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)));
}
$this->validators[$name] = new $name();
} elseif (is_string($this->validators[$name])) {
$this->validators[$name] = $this->container->get($this->validators[$name]);