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\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class RangeValidator extends ConstraintValidator
26 public function validate($value, Constraint $constraint)
28 if (!$constraint instanceof Range) {
29 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Range');
32 if (null === $value) {
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)
45 $min = $constraint->min;
46 $max = $constraint->max;
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);
57 if (\is_string($max)) {
58 $max = new \DateTime($max);
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)
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)