bug #40211 [Validator] fix taking error message from the correct violation (xabbuh)

This PR was merged into the 5.2 branch.

Discussion
----------

[Validator] fix taking error message from the correct violation

| Q             | A
| ------------- | ---
| Branch?       | 5.2
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #40082
| License       | MIT
| Doc PR        |

Commits
-------

32cd77aecc fix taking error message from the correct violation
This commit is contained in:
Christian Flothmann 2021-02-17 12:42:45 +01:00
commit b148f8935b
2 changed files with 36 additions and 1 deletions

View File

@ -48,7 +48,7 @@ class AtLeastOneOfValidator extends ConstraintValidator
if ($item instanceof All || $item instanceof Collection) {
$message .= $constraint->messageCollection;
} else {
$message .= $violations->get(0)->getMessage();
$message .= $violations->get(\count($violations) - 1)->getMessage();
}
$messages[] = $message;

View File

@ -206,6 +206,35 @@ class AtLeastOneOfValidatorTest extends ConstraintValidatorTestCase
$this->assertCount(0, $violations);
}
public function testEmbeddedMessageTakenFromFailingConstraint()
{
$validator = Validation::createValidatorBuilder()
->setMetadataFactory(new class() implements MetadataFactoryInterface {
public function getMetadataFor($classOrObject): MetadataInterface
{
return (new ClassMetadata(Data::class))
->addPropertyConstraint('foo', new NotNull(['message' => 'custom message foo']))
->addPropertyConstraint('bar', new AtLeastOneOf([
new NotNull(['message' => 'custom message bar']),
]))
;
}
public function hasMetadataFor($classOrObject): bool
{
return Data::class === $classOrObject;
}
})
->getValidator()
;
$violations = $validator->validate(new Data(), new Valid());
$this->assertCount(2, $violations);
$this->assertSame('custom message foo', $violations->get(0)->getMessage());
$this->assertSame('This value should satisfy at least one of the following constraints: [1] custom message bar', $violations->get(1)->getMessage());
}
}
class ExpressionConstraintNested
@ -217,3 +246,9 @@ class ExpressionConstraintNested
return 'bar';
}
}
class Data
{
public $foo;
public $bar;
}