ExpressionValidator.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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;
  22. public function __construct(ExpressionLanguage $expressionLanguage = null)
  23. {
  24. $this->expressionLanguage = $expressionLanguage;
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function validate($value, Constraint $constraint)
  30. {
  31. if (!$constraint instanceof Expression) {
  32. throw new UnexpectedTypeException($constraint, Expression::class);
  33. }
  34. $variables = $constraint->values;
  35. $variables['value'] = $value;
  36. $variables['this'] = $this->context->getObject();
  37. if (!$this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
  38. $this->context->buildViolation($constraint->message)
  39. ->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING))
  40. ->setCode(Expression::EXPRESSION_FAILED_ERROR)
  41. ->addViolation();
  42. }
  43. }
  44. private function getExpressionLanguage(): ExpressionLanguage
  45. {
  46. if (null === $this->expressionLanguage) {
  47. $this->expressionLanguage = new ExpressionLanguage();
  48. }
  49. return $this->expressionLanguage;
  50. }
  51. }