0aa0ed5e07787e4803e366b8a96a7c6f1b50aec8
[yaffs-website] / vendor / symfony / validator / Constraints / RegexValidator.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\Validator\Context\ExecutionContextInterface;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\ConstraintValidator;
17 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
18
19 /**
20  * Validates whether a value match or not given regexp pattern.
21  *
22  * @author Bernhard Schussek <bschussek@gmail.com>
23  * @author Joseph Bielawski <stloyd@gmail.com>
24  */
25 class RegexValidator extends ConstraintValidator
26 {
27     /**
28      * {@inheritdoc}
29      */
30     public function validate($value, Constraint $constraint)
31     {
32         if (!$constraint instanceof Regex) {
33             throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Regex');
34         }
35
36         if (null === $value || '' === $value) {
37             return;
38         }
39
40         if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
41             throw new UnexpectedTypeException($value, 'string');
42         }
43
44         $value = (string) $value;
45
46         if ($constraint->match xor preg_match($constraint->pattern, $value)) {
47             if ($this->context instanceof ExecutionContextInterface) {
48                 $this->context->buildViolation($constraint->message)
49                     ->setParameter('{{ value }}', $this->formatValue($value))
50                     ->setCode(Regex::REGEX_FAILED_ERROR)
51                     ->addViolation();
52             } else {
53                 $this->buildViolation($constraint->message)
54                     ->setParameter('{{ value }}', $this->formatValue($value))
55                     ->setCode(Regex::REGEX_FAILED_ERROR)
56                     ->addViolation();
57             }
58         }
59     }
60 }