DateTimeValidator.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace Symfony\Component\Validator\Constraints;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. class DateTimeValidator extends ConstraintValidator
  15. {
  16. 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])$/';
  17. public function isValid($value, Constraint $constraint)
  18. {
  19. if ($value === null || $value === '') {
  20. return true;
  21. }
  22. if ($value instanceof \DateTime) {
  23. return true;
  24. }
  25. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
  26. throw new UnexpectedTypeException($value, 'string');
  27. }
  28. $value = (string)$value;
  29. if (!preg_match(self::PATTERN, $value, $matches)) {
  30. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  31. return false;
  32. }
  33. return checkdate($matches[2], $matches[3], $matches[1]);
  34. }
  35. }