diff --git a/src/Symfony/Component/Validator/Constraints/AtLeastOneOfValidator.php b/src/Symfony/Component/Validator/Constraints/AtLeastOneOfValidator.php index 740313c76e..95558519d8 100644 --- a/src/Symfony/Component/Validator/Constraints/AtLeastOneOfValidator.php +++ b/src/Symfony/Component/Validator/Constraints/AtLeastOneOfValidator.php @@ -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; diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AtLeastOneOfValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AtLeastOneOfValidatorTest.php index b4fbab5575..6be6a5d6f7 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AtLeastOneOfValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AtLeastOneOfValidatorTest.php @@ -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; +}