diff --git a/src/Symfony/Component/Validator/ConstraintViolation.php b/src/Symfony/Component/Validator/ConstraintViolation.php index 804aa2cbe1..69781dc0ca 100644 --- a/src/Symfony/Component/Validator/ConstraintViolation.php +++ b/src/Symfony/Component/Validator/ConstraintViolation.php @@ -79,13 +79,13 @@ class ConstraintViolation implements ConstraintViolationInterface } $propertyPath = (string) $this->propertyPath; - $code = $this->code; + $code = (string) $this->code; if ('' !== $propertyPath && '[' !== $propertyPath[0] && '' !== $class) { $class .= '.'; } - if (!empty($code)) { + if ('' !== $code) { $code = ' (code '.$code.')'; } diff --git a/src/Symfony/Component/Validator/Tests/ConstraintViolationTest.php b/src/Symfony/Component/Validator/Tests/ConstraintViolationTest.php index cef4782e0f..edaa7fa50d 100644 --- a/src/Symfony/Component/Validator/Tests/ConstraintViolationTest.php +++ b/src/Symfony/Component/Validator/Tests/ConstraintViolationTest.php @@ -53,4 +53,59 @@ EOF; $this->assertSame($expected, (string) $violation); } + + public function testToStringHandlesCodes() + { + $violation = new ConstraintViolation( + '42 cannot be used here', + 'this is the message template', + array(), + array('some_value' => 42), + 'some_value', + null, + null, + 0 + ); + + $expected = <<<'EOF' +Array.some_value: + 42 cannot be used here (code 0) +EOF; + + $this->assertSame($expected, (string) $violation); + } + + public function testToStringOmitsEmptyCodes() + { + $expected = <<<'EOF' +Array.some_value: + 42 cannot be used here +EOF; + + $violation = new ConstraintViolation( + '42 cannot be used here', + 'this is the message template', + array(), + array('some_value' => 42), + 'some_value', + null, + null, + null + ); + + $this->assertSame($expected, (string) $violation); + + $violation = new ConstraintViolation( + '42 cannot be used here', + 'this is the message template', + array(), + array('some_value' => 42), + 'some_value', + null, + null, + '' + ); + + $this->assertSame($expected, (string) $violation); + } }