Skip to content

Commit 39bcf80

Browse files
bug #29375 [Validator] Allow ConstraintViolation::__toString() to expose codes that are not null or emtpy strings (phansys)
This PR was squashed before being merged into the 3.4 branch (closes #29375). Discussion ---------- [Validator] Allow `ConstraintViolation::__toString()` to expose codes that are not null or emtpy strings |Q |A | |--- |---| |Branch |2.8| |Bug fix? |yes| |New feature? |no | |BC breaks? |no | |Deprecations?|no | |Tests pass? |yes| |Fixed tickets|n/a| |License |MIT| |Doc PR |n/a| Allow to expose `0` or `"0"` validation codes. Commits ------- 7bb0fb5cc3 [Validator] Allow `ConstraintViolation::__toString()` to expose codes that are not null or emtpy strings
2 parents 661d7d0 + dbb6232 commit 39bcf80

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

ConstraintViolation.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,13 @@ public function __toString()
7979
}
8080

8181
$propertyPath = (string) $this->propertyPath;
82-
$code = $this->code;
82+
$code = (string) $this->code;
8383

8484
if ('' !== $propertyPath && '[' !== $propertyPath[0] && '' !== $class) {
8585
$class .= '.';
8686
}
8787

88-
if (!empty($code)) {
88+
if ('' !== $code) {
8989
$code = ' (code '.$code.')';
9090
}
9191

Tests/ConstraintViolationTest.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,59 @@ public function testToStringHandlesArrayRoots()
5353

5454
$this->assertSame($expected, (string) $violation);
5555
}
56+
57+
public function testToStringHandlesCodes()
58+
{
59+
$violation = new ConstraintViolation(
60+
'42 cannot be used here',
61+
'this is the message template',
62+
array(),
63+
array('some_value' => 42),
64+
'some_value',
65+
null,
66+
null,
67+
0
68+
);
69+
70+
$expected = <<<'EOF'
71+
Array.some_value:
72+
42 cannot be used here (code 0)
73+
EOF;
74+
75+
$this->assertSame($expected, (string) $violation);
76+
}
77+
78+
public function testToStringOmitsEmptyCodes()
79+
{
80+
$expected = <<<'EOF'
81+
Array.some_value:
82+
42 cannot be used here
83+
EOF;
84+
85+
$violation = new ConstraintViolation(
86+
'42 cannot be used here',
87+
'this is the message template',
88+
array(),
89+
array('some_value' => 42),
90+
'some_value',
91+
null,
92+
null,
93+
null
94+
);
95+
96+
$this->assertSame($expected, (string) $violation);
97+
98+
$violation = new ConstraintViolation(
99+
'42 cannot be used here',
100+
'this is the message template',
101+
array(),
102+
array('some_value' => 42),
103+
'some_value',
104+
null,
105+
null,
106+
''
107+
);
108+
109+
$this->assertSame($expected, (string) $violation);
110+
}
56111
}

0 commit comments

Comments
 (0)