ExpressionLanguageSyntaxValidator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  12. use Symfony\Component\ExpressionLanguage\SyntaxError;
  13. use Symfony\Component\Validator\Constraint;
  14. use Symfony\Component\Validator\ConstraintValidator;
  15. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  16. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  17. /**
  18. * @author Andrey Sevastianov <mrpkmail@gmail.com>
  19. */
  20. class ExpressionLanguageSyntaxValidator extends ConstraintValidator
  21. {
  22. private $expressionLanguage;
  23. public function __construct(ExpressionLanguage $expressionLanguage = null)
  24. {
  25. $this->expressionLanguage = $expressionLanguage;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function validate($expression, Constraint $constraint): void
  31. {
  32. if (!$constraint instanceof ExpressionLanguageSyntax) {
  33. throw new UnexpectedTypeException($constraint, ExpressionLanguageSyntax::class);
  34. }
  35. if (!\is_string($expression)) {
  36. throw new UnexpectedValueException($expression, 'string');
  37. }
  38. if (null === $this->expressionLanguage) {
  39. $this->expressionLanguage = new ExpressionLanguage();
  40. }
  41. try {
  42. $this->expressionLanguage->lint($expression, $constraint->allowedVariables);
  43. } catch (SyntaxError $exception) {
  44. $this->context->buildViolation($constraint->message)
  45. ->setParameter('{{ syntax_error }}', $this->formatValue($exception->getMessage()))
  46. ->setInvalidValue((string) $expression)
  47. ->setCode(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
  48. ->addViolation();
  49. }
  50. }
  51. }