[Validator] Improved dynamic constraints
This commit is contained in:
parent
54cb6e458e
commit
09c191136a
@ -12,6 +12,7 @@
|
||||
namespace Symfony\Component\Validator;
|
||||
|
||||
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
|
||||
use Symfony\Component\Validator\Mapping\ClassMetadata;
|
||||
|
||||
/**
|
||||
* The default implementation of the ValidatorInterface.
|
||||
@ -59,7 +60,10 @@ class Validator implements ValidatorInterface
|
||||
$metadata = $this->metadataFactory->getClassMetadata(get_class($object));
|
||||
|
||||
if ($object instanceof ConstraintProviderInterface) {
|
||||
$object->getConstraints($metadata);
|
||||
$dynamicMetadata = new ClassMetadata(get_class($object));
|
||||
$dynamicMetadata->mergeConstraints($metadata);
|
||||
$object->getConstraints($dynamicMetadata);
|
||||
$metadata = $dynamicMetadata;
|
||||
}
|
||||
|
||||
$walk = function(GraphWalker $walker, $group) use ($metadata, $object) {
|
||||
|
@ -7,15 +7,24 @@ use Symfony\Component\Validator\Mapping\ClassMetadata;
|
||||
|
||||
class DynamicConstraintsEntity implements ConstraintProviderInterface
|
||||
{
|
||||
protected $validationEnabled = false;
|
||||
protected $firstValue;
|
||||
|
||||
public function getSecondValue() {
|
||||
public function setValidation($enabled)
|
||||
{
|
||||
$this->validationEnabled = $enabled;
|
||||
}
|
||||
|
||||
public function getSecondValue()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getConstraints(ClassMetadata $metadata)
|
||||
{
|
||||
$metadata->addPropertyConstraint('firstValue', new FailingConstraint());
|
||||
$metadata->addGetterConstraint('secondValue', new FailingConstraint());
|
||||
if ($this->validationEnabled) {
|
||||
$metadata->addPropertyConstraint('firstValue', new FailingConstraint());
|
||||
$metadata->addGetterConstraint('secondValue', new FailingConstraint());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -129,8 +129,9 @@ class ValidatorTest extends \PHPUnit_Framework_TestCase
|
||||
$entity = new DynamicConstraintsEntity();
|
||||
$metadata = new ClassMetadata(get_class($entity));
|
||||
$this->factory->addClassMetadata($metadata);
|
||||
|
||||
$entity->setValidation(true);
|
||||
|
||||
// Only the constraint of group "Default" failed
|
||||
$violations = new ConstraintViolationList();
|
||||
$violations->add(new ConstraintViolation(
|
||||
'',
|
||||
@ -146,7 +147,12 @@ class ValidatorTest extends \PHPUnit_Framework_TestCase
|
||||
'secondValue',
|
||||
''
|
||||
));
|
||||
|
||||
|
||||
$this->assertEquals($violations, $this->validator->validate($entity));
|
||||
|
||||
$entity->setValidation(false);
|
||||
|
||||
$violations = new ConstraintViolationList();
|
||||
$this->assertEquals($violations, $this->validator->validate($entity));
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user