DateTimeValidator.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace Symfony\Component\Validator\Constraints;
  3. use Symfony\Component\Validator\Constraint;
  4. use Symfony\Component\Validator\ConstraintValidator;
  5. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  6. class DateTimeValidator extends ConstraintValidator
  7. {
  8. const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';
  9. public function isValid($value, Constraint $constraint)
  10. {
  11. if ($value === null) {
  12. return true;
  13. }
  14. if ($value instanceof \DateTime) {
  15. return true;
  16. }
  17. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
  18. throw new UnexpectedTypeException($value, 'string');
  19. }
  20. $value = (string)$value;
  21. if (!preg_match(self::PATTERN, $value, $matches)) {
  22. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  23. return false;
  24. }
  25. return checkdate($matches[2], $matches[3], $matches[1]);
  26. }
  27. }