e2f3139af73b85652904c5ea7bb53d85c26e38c2
[yaffs-website] / vendor / symfony / validator / Constraints / ExpressionValidator.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Validator\Constraints;
13
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;
19
20 /**
21  * @author Fabien Potencier <fabien@symfony.com>
22  * @author Bernhard Schussek <bschussek@symfony.com>
23  */
24 class ExpressionValidator extends ConstraintValidator
25 {
26     /**
27      * @var ExpressionLanguage
28      */
29     private $expressionLanguage;
30
31     public function __construct($propertyAccessor = null, ExpressionLanguage $expressionLanguage = null)
32     {
33         $this->expressionLanguage = $expressionLanguage;
34     }
35
36     /**
37      * {@inheritdoc}
38      */
39     public function validate($value, Constraint $constraint)
40     {
41         if (!$constraint instanceof Expression) {
42             throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression');
43         }
44
45         $variables = array();
46         $variables['value'] = $value;
47         $variables['this'] = $this->context->getObject();
48
49         if (!$this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
50             $this->context->buildViolation($constraint->message)
51                 ->setParameter('{{ value }}', $this->formatValue($value))
52                 ->setCode(Expression::EXPRESSION_FAILED_ERROR)
53                 ->addViolation();
54         }
55     }
56
57     private function getExpressionLanguage()
58     {
59         if (null === $this->expressionLanguage) {
60             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
61                 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
62             }
63             $this->expressionLanguage = new ExpressionLanguage();
64         }
65
66         return $this->expressionLanguage;
67     }
68 }