Skip to content

[FrameworkBundle] Added friendly exception when constraint validator class does not exist #19601

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,19 @@ public function testGetInstanceReturnsService()
$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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
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;

/**
Expand Down Expand Up @@ -61,13 +62,18 @@ public function __construct(ContainerInterface $container, array $validators = a
*
* @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)
{
$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]);
Expand Down