Date.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use Respect\Validation\Exceptions\ComponentException;
  9. use Respect\Validation\Helpers\CanValidateDateTime;
  10. use function date;
  11. use function is_scalar;
  12. use function preg_match;
  13. use function sprintf;
  14. use function strtotime;
  15. /**
  16. * Validates if input is a date.
  17. *
  18. * @author Bruno Luiz da Silva <contato@brunoluiz.net>
  19. * @author Henrique Moody <henriquemoody@gmail.com>
  20. */
  21. final class Date extends AbstractRule
  22. {
  23. use CanValidateDateTime;
  24. /**
  25. * @var string
  26. */
  27. private $format;
  28. /**
  29. * @var string
  30. */
  31. private $sample;
  32. /**
  33. * Initializes the rule.
  34. *
  35. * @throws ComponentException
  36. */
  37. public function __construct(string $format = 'Y-m-d')
  38. {
  39. if (!preg_match('/^[djSFmMnYy\W]+$/', $format)) {
  40. throw new ComponentException(sprintf('"%s" is not a valid date format', $format));
  41. }
  42. $this->format = $format;
  43. $this->sample = date($format, strtotime('2005-12-30'));
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function validate($input): bool
  49. {
  50. if (!is_scalar($input)) {
  51. return false;
  52. }
  53. return $this->isDateTime($this->format, (string) $input);
  54. }
  55. }