ac140dbbf34e2c1b915fc41969903f49aa95d547
[yaffs-website] / vendor / symfony / validator / Constraints / RangeValidator.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\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
17
18 /**
19  * @author Bernhard Schussek <bschussek@gmail.com>
20  */
21 class RangeValidator extends ConstraintValidator
22 {
23     /**
24      * {@inheritdoc}
25      */
26     public function validate($value, Constraint $constraint)
27     {
28         if (!$constraint instanceof Range) {
29             throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Range');
30         }
31
32         if (null === $value) {
33             return;
34         }
35
36         if (!is_numeric($value) && !$value instanceof \DateTimeInterface) {
37             $this->context->buildViolation($constraint->invalidMessage)
38                 ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
39                 ->setCode(Range::INVALID_CHARACTERS_ERROR)
40                 ->addViolation();
41
42             return;
43         }
44
45         $min = $constraint->min;
46         $max = $constraint->max;
47
48         // Convert strings to DateTimes if comparing another DateTime
49         // This allows to compare with any date/time value supported by
50         // the DateTime constructor:
51         // http://php.net/manual/en/datetime.formats.php
52         if ($value instanceof \DateTimeInterface) {
53             if (is_string($min)) {
54                 $min = new \DateTime($min);
55             }
56
57             if (is_string($max)) {
58                 $max = new \DateTime($max);
59             }
60         }
61
62         if (null !== $constraint->max && $value > $max) {
63             $this->context->buildViolation($constraint->maxMessage)
64                 ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
65                 ->setParameter('{{ limit }}', $this->formatValue($max, self::PRETTY_DATE))
66                 ->setCode(Range::TOO_HIGH_ERROR)
67                 ->addViolation();
68
69             return;
70         }
71
72         if (null !== $constraint->min && $value < $min) {
73             $this->context->buildViolation($constraint->minMessage)
74                 ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
75                 ->setParameter('{{ limit }}', $this->formatValue($min, self::PRETTY_DATE))
76                 ->setCode(Range::TOO_LOW_ERROR)
77                 ->addViolation();
78         }
79     }
80 }