DateValidator.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  15. /**
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class DateValidator extends ConstraintValidator
  19. {
  20. public const PATTERN = '/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/';
  21. /**
  22. * Checks whether a date is valid.
  23. *
  24. * @internal
  25. */
  26. public static function checkDate(int $year, int $month, int $day): bool
  27. {
  28. return checkdate($month, $day, $year);
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function validate($value, Constraint $constraint)
  34. {
  35. if (!$constraint instanceof Date) {
  36. throw new UnexpectedTypeException($constraint, Date::class);
  37. }
  38. if (null === $value || '' === $value) {
  39. return;
  40. }
  41. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  42. throw new UnexpectedValueException($value, 'string');
  43. }
  44. $value = (string) $value;
  45. if (!preg_match(static::PATTERN, $value, $matches)) {
  46. $this->context->buildViolation($constraint->message)
  47. ->setParameter('{{ value }}', $this->formatValue($value))
  48. ->setCode(Date::INVALID_FORMAT_ERROR)
  49. ->addViolation();
  50. return;
  51. }
  52. if (!self::checkDate(
  53. $matches['year'] ?? $matches[1],
  54. $matches['month'] ?? $matches[2],
  55. $matches['day'] ?? $matches[3]
  56. )) {
  57. $this->context->buildViolation($constraint->message)
  58. ->setParameter('{{ value }}', $this->formatValue($value))
  59. ->setCode(Date::INVALID_DATE_ERROR)
  60. ->addViolation();
  61. }
  62. }
  63. }