4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\ConstraintValidator;
17 use Symfony\Component\Validator\Exception\RuntimeException;
18 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
21 * @author Fabien Potencier <fabien@symfony.com>
22 * @author Bernhard Schussek <bschussek@symfony.com>
24 class ExpressionValidator extends ConstraintValidator
26 private $expressionLanguage;
28 public function __construct($propertyAccessor = null, ExpressionLanguage $expressionLanguage = null)
30 $this->expressionLanguage = $expressionLanguage;
36 public function validate($value, Constraint $constraint)
38 if (!$constraint instanceof Expression) {
39 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression');
43 $variables['value'] = $value;
44 $variables['this'] = $this->context->getObject();
46 if (!$this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
47 $this->context->buildViolation($constraint->message)
48 ->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING))
49 ->setCode(Expression::EXPRESSION_FAILED_ERROR)
54 private function getExpressionLanguage()
56 if (null === $this->expressionLanguage) {
57 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
58 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
60 $this->expressionLanguage = new ExpressionLanguage();
63 return $this->expressionLanguage;