Skip to content

Commit

Permalink
feature #31083 [Validator] Allow objects implementing __toString() to…
Browse files Browse the repository at this point in the history
… be used as violation messages (mdlutz24)

This PR was merged into the 4.4 branch.

Discussion
----------

[Validator] Allow objects implementing __toString() to be used as violation messages

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT
| Doc PR        | I didn't see a doc on violations to update, but I'm happy to do documentation if somone can suggest the best place to do it.

Currently in the Drupal project we use Translatable Markup object to hold most strings and currently pass them in as Constraint Violation messages. In Symfony 3 this works but with the added typehinting in Symfony 4, these markup objects are rendered into strings at the time of the violation creation.  This causes any html in the message string to be considered unsafe by twig later in our rendering process.  This pr explicitly allows objects implementing a __toString() method to be used as violation messages, and the violation will save and return the original stringable object.

See https://www.drupal.org/project/drupal/issues/3029540 For our Drupal issue on the subject.

Commits
-------

79f4dcd [Validator] Allow objects implementing __toString() to be used as violation messages
  • Loading branch information
fabpot committed Aug 9, 2019
2 parents 6888e70 + 79f4dcd commit 5ce3a61
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Expand Up @@ -20,6 +20,7 @@ CHANGELOG
`maxPropertyPath` options
* added a new `notInRangeMessage` option to the `Range` constraint that will
be used in the violation builder when both `min` and `max` are not null
* added ability to use stringable objects as violation messages

4.3.0
-----
Expand Down
8 changes: 6 additions & 2 deletions src/Symfony/Component/Validator/ConstraintViolation.php
Expand Up @@ -32,7 +32,7 @@ class ConstraintViolation implements ConstraintViolationInterface
/**
* Creates a new constraint violation.
*
* @param string $message The violation message
* @param string $message The violation message as a string or a stringable object
* @param string $messageTemplate The raw violation message
* @param array $parameters The parameters to substitute in the
* raw violation message
Expand All @@ -47,7 +47,7 @@ class ConstraintViolation implements ConstraintViolationInterface
* @param string|null $code The error code of the violation
* @param mixed $cause The cause of the violation
*/
public function __construct(?string $message, ?string $messageTemplate, array $parameters, $root, ?string $propertyPath, $invalidValue, int $plural = null, $code = null, Constraint $constraint = null, $cause = null)
public function __construct($message, ?string $messageTemplate, array $parameters, $root, ?string $propertyPath, $invalidValue, int $plural = null, $code = null, Constraint $constraint = null, $cause = null)
{
if (null === $message) {
@trigger_error(sprintf('Passing a null message when instantiating a "%s" is deprecated since Symfony 4.4.', __CLASS__), E_USER_DEPRECATED);
Expand All @@ -58,6 +58,10 @@ public function __construct(?string $message, ?string $messageTemplate, array $p
@trigger_error(sprintf('Not using a string as the error code in %s() is deprecated since Symfony 4.4. A type-hint will be added in 5.0.', __METHOD__), E_USER_DEPRECATED);
}

if (!\is_string($message) && !(\is_object($message) && method_exists($message, '__toString'))) {
throw new \TypeError('Constraint violation message should be a string or an object which implements the __toString() method.');
}

$this->message = $message;
$this->messageTemplate = $messageTemplate;
$this->parameters = $parameters;
Expand Down
Expand Up @@ -36,7 +36,7 @@ interface ConstraintViolationInterface
/**
* Returns the violation message.
*
* @return string The violation message
* @return string The violation message as a string or a stringable object
*/
public function getMessage();

Expand Down
Expand Up @@ -64,7 +64,7 @@ interface ExecutionContextInterface
/**
* Adds a violation at the current node of the validation graph.
*
* @param string $message The error message
* @param string $message The error message as a string or a stringable object
* @param array $params The parameters substituted in the error message
*/
public function addViolation($message, array $params = []);
Expand All @@ -81,7 +81,7 @@ public function addViolation($message, array $params = []);
* ->setTranslationDomain('number_validation')
* ->addViolation();
*
* @param string $message The error message
* @param string $message The error message as a string or a stringable object
* @param array $parameters The parameters substituted in the error message
*
* @return ConstraintViolationBuilderInterface The violation builder
Expand Down
48 changes: 48 additions & 0 deletions src/Symfony/Component/Validator/Tests/ConstraintViolationTest.php
Expand Up @@ -13,6 +13,8 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Tests\Fixtures\CustomArrayObject;
use Symfony\Component\Validator\Tests\Fixtures\ToString;

class ConstraintViolationTest extends TestCase
{
Expand Down Expand Up @@ -109,6 +111,52 @@ public function testToStringOmitsEmptyCodes()
$this->assertSame($expected, (string) $violation);
}

public function testMessageCanBeStringableObject()
{
$message = new ToString();
$violation = new ConstraintViolation(
$message,
(string) $message,
[],
'Root',
'property.path',
null
);

$expected = <<<'EOF'
Root.property.path:
toString
EOF;
$this->assertSame($expected, (string) $violation);
$this->assertSame($message, $violation->getMessage());
}

public function testMessageCannotBeArray()
{
$this->expectException(\TypeError::class);
$violation = new ConstraintViolation(
['cannot be an array'],
'',
[],
'Root',
'property.path',
null
);
}

public function testMessageObjectMustBeStringable()
{
$this->expectException(\TypeError::class);
$violation = new ConstraintViolation(
new CustomArrayObject(),
'',
[],
'Root',
'property.path',
null
);
}

/**
* @group legacy
* @expectedDeprecation Not using a string as the error code in Symfony\Component\Validator\ConstraintViolation::__construct() is deprecated since Symfony 4.4. A type-hint will be added in 5.0.
Expand Down
Expand Up @@ -45,9 +45,10 @@ class ConstraintViolationBuilder implements ConstraintViolationBuilderInterface
private $cause;

/**
* @param string $message The error message as a string or a stringable object
* @param TranslatorInterface $translator
*/
public function __construct(ConstraintViolationList $violations, Constraint $constraint, ?string $message, array $parameters, $root, string $propertyPath, $invalidValue, $translator, string $translationDomain = null)
public function __construct(ConstraintViolationList $violations, Constraint $constraint, $message, array $parameters, $root, string $propertyPath, $invalidValue, $translator, string $translationDomain = null)
{
if (null === $message) {
@trigger_error(sprintf('Passing a null message when instantiating a "%s" is deprecated since Symfony 4.4.', __CLASS__), E_USER_DEPRECATED);
Expand Down

0 comments on commit 5ce3a61

Please sign in to comment.