Security update for Core, with self-updated composer
[yaffs-website] / vendor / symfony / validator / Constraints / DateValidator.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 DateValidator extends ConstraintValidator
22 {
23     const PATTERN = '/^(\d{4})-(\d{2})-(\d{2})$/';
24
25     /**
26      * Checks whether a date is valid.
27      *
28      * @param int $year  The year
29      * @param int $month The month
30      * @param int $day   The day
31      *
32      * @return bool Whether the date is valid
33      *
34      * @internal
35      */
36     public static function checkDate($year, $month, $day)
37     {
38         return checkdate($month, $day, $year);
39     }
40
41     /**
42      * {@inheritdoc}
43      */
44     public function validate($value, Constraint $constraint)
45     {
46         if (!$constraint instanceof Date) {
47             throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Date');
48         }
49
50         if (null === $value || '' === $value || $value instanceof \DateTimeInterface) {
51             return;
52         }
53
54         if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
55             throw new UnexpectedTypeException($value, 'string');
56         }
57
58         $value = (string) $value;
59
60         if (!preg_match(static::PATTERN, $value, $matches)) {
61             $this->context->buildViolation($constraint->message)
62                 ->setParameter('{{ value }}', $this->formatValue($value))
63                 ->setCode(Date::INVALID_FORMAT_ERROR)
64                 ->addViolation();
65
66             return;
67         }
68
69         if (!self::checkDate($matches[1], $matches[2], $matches[3])) {
70             $this->context->buildViolation($constraint->message)
71                 ->setParameter('{{ value }}', $this->formatValue($value))
72                 ->setCode(Date::INVALID_DATE_ERROR)
73                 ->addViolation();
74         }
75     }
76 }