[Validator] use "allowedVariables" to configure the ExpressionLanguageSyntax constraint

This commit is contained in:
Christian Flothmann 2020-05-30 10:18:13 +02:00 committed by Nicolas Grekas
parent 2ff26b7ce8
commit 4807dab305
3 changed files with 7 additions and 6 deletions

View File

@ -29,8 +29,7 @@ class ExpressionLanguageSyntax extends Constraint
public $message = 'This value should be a valid expression.';
public $service;
public $validateNames = true;
public $names = [];
public $allowedVariables = null;
/**
* {@inheritdoc}

View File

@ -16,6 +16,7 @@ use Symfony\Component\ExpressionLanguage\SyntaxError;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
/**
* @author Andrey Sevastianov <mrpkmail@gmail.com>
@ -39,7 +40,7 @@ class ExpressionLanguageSyntaxValidator extends ConstraintValidator
}
if (!\is_string($expression)) {
throw new UnexpectedTypeException($expression, 'string');
throw new UnexpectedValueException($expression, 'string');
}
if (null === $this->expressionLanguage) {
@ -47,7 +48,7 @@ class ExpressionLanguageSyntaxValidator extends ConstraintValidator
}
try {
$this->expressionLanguage->lint($expression, ($constraint->validateNames ? ($constraint->names ?? []) : null));
$this->expressionLanguage->lint($expression, $constraint->allowedVariables);
} catch (SyntaxError $exception) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ syntax_error }}', $this->formatValue($exception->getMessage()))

View File

@ -18,7 +18,7 @@ use Symfony\Component\Validator\Constraints\ExpressionLanguageSyntax;
use Symfony\Component\Validator\Constraints\ExpressionLanguageSyntaxValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
class ExpressionLanguageSyntaxTest extends ConstraintValidatorTestCase
class ExpressionLanguageSyntaxValidatorTest extends ConstraintValidatorTestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|ExpressionLanguage
@ -45,6 +45,7 @@ class ExpressionLanguageSyntaxTest extends ConstraintValidatorTestCase
$this->validator->validate($this->value, new ExpressionLanguageSyntax([
'message' => 'myMessage',
'allowedVariables' => [],
]));
$this->assertNoViolation();
@ -58,7 +59,6 @@ class ExpressionLanguageSyntaxTest extends ConstraintValidatorTestCase
$this->validator->validate($this->value, new ExpressionLanguageSyntax([
'message' => 'myMessage',
'validateNames' => false,
]));
$this->assertNoViolation();
@ -73,6 +73,7 @@ class ExpressionLanguageSyntaxTest extends ConstraintValidatorTestCase
$this->validator->validate($this->value, new ExpressionLanguageSyntax([
'message' => 'myMessage',
'allowedVariables' => [],
]));
$this->buildViolation('myMessage')