[Validator] ExpressionValidator should use OBJECT_TO_STRING to allow value in message

This commit is contained in:
Amrouche Hamza 2017-10-30 06:23:08 +01:00
parent e2c608ae6b
commit 7dac528a86
No known key found for this signature in database
GPG Key ID: 6968F2785ED4F012
3 changed files with 58 additions and 2 deletions

View File

@ -78,11 +78,11 @@ class ExpressionValidator extends ConstraintValidator
if (!$this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING))
->addViolation();
} else {
$this->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING))
->addViolation();
}
}

View File

@ -15,6 +15,7 @@ use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\ToString;
use Symfony\Component\Validator\Validation;
class ExpressionValidatorTest extends AbstractConstraintValidatorTest
@ -90,6 +91,39 @@ class ExpressionValidatorTest extends AbstractConstraintValidatorTest
->assertRaised();
}
public function testSucceedingExpressionAtObjectLevelWithToString()
{
$constraint = new Expression('this.data == 1');
$object = new ToString();
$object->data = '1';
$this->setObject($object);
$this->validator->validate($object, $constraint);
$this->assertNoViolation();
}
public function testFailingExpressionAtObjectLevelWithToString()
{
$constraint = new Expression(array(
'expression' => 'this.data == 1',
'message' => 'myMessage',
));
$object = new ToString();
$object->data = '2';
$this->setObject($object);
$this->validator->validate($object, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'toString')
->assertRaised();
}
public function testSucceedingExpressionAtPropertyLevel()
{
$constraint = new Expression('value == this.data');

View File

@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Fixtures;
class ToString
{
public $data;
public function __toString()
{
return 'toString';
}
}