vendor/symfony/validator/Constraints/ExpressionSyntaxValidator.php line 28

  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 ExpressionSyntaxValidator extends ConstraintValidator
  21. {
  22.     private ?ExpressionLanguage $expressionLanguage;
  23.     public function __construct(ExpressionLanguage $expressionLanguage null)
  24.     {
  25.         $this->expressionLanguage $expressionLanguage;
  26.     }
  27.     public function validate(mixed $expressionConstraint $constraint): void
  28.     {
  29.         if (!$constraint instanceof ExpressionSyntax) {
  30.             throw new UnexpectedTypeException($constraintExpressionSyntax::class);
  31.         }
  32.         if (null === $expression || '' === $expression) {
  33.             return;
  34.         }
  35.         if (!\is_string($expression)) {
  36.             throw new UnexpectedValueException($expression'string');
  37.         }
  38.         $this->expressionLanguage ??= new ExpressionLanguage();
  39.         try {
  40.             $this->expressionLanguage->lint($expression$constraint->allowedVariables);
  41.         } catch (SyntaxError $exception) {
  42.             $this->context->buildViolation($constraint->message)
  43.                 ->setParameter('{{ syntax_error }}'$this->formatValue($exception->getMessage()))
  44.                 ->setInvalidValue((string) $expression)
  45.                 ->setCode(ExpressionSyntax::EXPRESSION_SYNTAX_ERROR)
  46.                 ->addViolation();
  47.         }
  48.     }
  49. }