Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b148f89

Browse files
committed
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 ------- 32cd77a fix taking error message from the correct violation
2 parents 7dcf156 + 32cd77a commit b148f89

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/Symfony/Component/Validator/Constraints/AtLeastOneOfValidator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public function validate($value, Constraint $constraint)
4848
if ($item instanceof All || $item instanceof Collection) {
4949
$message .= $constraint->messageCollection;
5050
} else {
51-
$message .= $violations->get(0)->getMessage();
51+
$message .= $violations->get(\count($violations) - 1)->getMessage();
5252
}
5353

5454
$messages[] = $message;

src/Symfony/Component/Validator/Tests/Constraints/AtLeastOneOfValidatorTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,35 @@ public function hasMetadataFor($classOrObject): bool
206206

207207
$this->assertCount(0, $violations);
208208
}
209+
210+
public function testEmbeddedMessageTakenFromFailingConstraint()
211+
{
212+
$validator = Validation::createValidatorBuilder()
213+
->setMetadataFactory(new class() implements MetadataFactoryInterface {
214+
public function getMetadataFor($classOrObject): MetadataInterface
215+
{
216+
return (new ClassMetadata(Data::class))
217+
->addPropertyConstraint('foo', new NotNull(['message' => 'custom message foo']))
218+
->addPropertyConstraint('bar', new AtLeastOneOf([
219+
new NotNull(['message' => 'custom message bar']),
220+
]))
221+
;
222+
}
223+
224+
public function hasMetadataFor($classOrObject): bool
225+
{
226+
return Data::class === $classOrObject;
227+
}
228+
})
229+
->getValidator()
230+
;
231+
232+
$violations = $validator->validate(new Data(), new Valid());
233+
234+
$this->assertCount(2, $violations);
235+
$this->assertSame('custom message foo', $violations->get(0)->getMessage());
236+
$this->assertSame('This value should satisfy at least one of the following constraints: [1] custom message bar', $violations->get(1)->getMessage());
237+
}
209238
}
210239

211240
class ExpressionConstraintNested
@@ -217,3 +246,9 @@ public function getFoobar(): string
217246
return 'bar';
218247
}
219248
}
249+
250+
class Data
251+
{
252+
public $foo;
253+
public $bar;
254+
}

0 commit comments

Comments
 (0)