RangeConstraintValidator.php in Drupal 8
File
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/RangeConstraintValidator.php
View source
<?php
namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class RangeConstraintValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint) {
if (!$constraint instanceof Range) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Range');
}
if (NULL === $value) {
return;
}
if (!is_numeric($value) && !$value instanceof \DateTimeInterface) {
$this->context
->buildViolation($constraint->invalidMessage)
->setParameter('{{ value }}', $this
->formatValue($value, self::PRETTY_DATE))
->setCode(Range::INVALID_CHARACTERS_ERROR)
->addViolation();
return;
}
$min = $constraint->min;
$max = $constraint->max;
if ($value instanceof \DateTimeInterface) {
if (\is_string($min)) {
$min = new \DateTime($min);
}
if (\is_string($max)) {
$max = new \DateTime($max);
}
}
if (NULL !== $constraint->max && $value > $max) {
$this->context
->buildViolation($constraint->maxMessage)
->setParameter('{{ value }}', $this
->formatValue($value, self::PRETTY_DATE))
->setParameter('{{ limit }}', $this
->formatValue($max, self::PRETTY_DATE))
->setCode(Range::TOO_HIGH_ERROR)
->addViolation();
return;
}
if (NULL !== $constraint->min && $value < $min) {
$this->context
->buildViolation($constraint->minMessage)
->setParameter('{{ value }}', $this
->formatValue($value, self::PRETTY_DATE))
->setParameter('{{ limit }}', $this
->formatValue($min, self::PRETTY_DATE))
->setCode(Range::TOO_LOW_ERROR)
->addViolation();
}
}
}