Skip to content

[Validator] Ensure nested validations for Collections happen in a separate context #14786

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 @@ -60,7 +60,7 @@ public function validate($value, Constraint $constraint)
if (count($fieldConstraint->constraints) > 0) {
if ($context instanceof ExecutionContextInterface) {
$context->getValidator()
->inContext($context)
->inContext(clone $context)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This solution doesn't work. Now all constraints thrown by the validators in the Collection constraint will be added to the cloned context and not appear in the current context (which is the point of calling inContext()).

->atPath('['.$field.']')
->validate($value[$field], $fieldConstraint->constraints);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Tests\Validator;

use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\GroupSequence;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Traverse;
Expand Down Expand Up @@ -773,4 +774,22 @@ public function testPassConstraintToViolation()
$this->assertCount(1, $violations);
$this->assertSame($constraint, $violations[0]->getConstraint());
}

public function testCollectionConstraitViolationHasCorrectContext()
{
$data = array(
'foo' => 'fooValue',
);

// Missing field must not be the first in the collection validation
$constraint = new Collection(array(
'foo' => new NotNull(),
'bar' => new NotNull(),
));

$violations = $this->validate($data, $constraint);

$this->assertCount(1, $violations);
$this->assertSame($constraint, $violations[0]->getConstraint());
}
}