vendor/symfony/validator/Constraints/ExpressionValidator.php line 27

  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\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. /**
  16.  * @author Fabien Potencier <fabien@symfony.com>
  17.  * @author Bernhard Schussek <bschussek@symfony.com>
  18.  */
  19. class ExpressionValidator extends ConstraintValidator
  20. {
  21.     private ?ExpressionLanguage $expressionLanguage;
  22.     public function __construct(ExpressionLanguage $expressionLanguage null)
  23.     {
  24.         $this->expressionLanguage $expressionLanguage;
  25.     }
  26.     public function validate(mixed $valueConstraint $constraint)
  27.     {
  28.         if (!$constraint instanceof Expression) {
  29.             throw new UnexpectedTypeException($constraintExpression::class);
  30.         }
  31.         $variables $constraint->values;
  32.         $variables['value'] = $value;
  33.         $variables['this'] = $this->context->getObject();
  34.         if ($constraint->negate xor $this->getExpressionLanguage()->evaluate($constraint->expression$variables)) {
  35.             $this->context->buildViolation($constraint->message)
  36.                 ->setParameter('{{ value }}'$this->formatValue($valueself::OBJECT_TO_STRING))
  37.                 ->setCode(Expression::EXPRESSION_FAILED_ERROR)
  38.                 ->addViolation();
  39.         }
  40.     }
  41.     private function getExpressionLanguage(): ExpressionLanguage
  42.     {
  43.         return $this->expressionLanguage ??= new ExpressionLanguage();
  44.     }
  45. }