DateTime.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 DateTimeInterface;
  9. use Respect\Validation\Helpers\CanValidateDateTime;
  10. use function date;
  11. use function is_scalar;
  12. use function strtotime;
  13. /**
  14. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  15. * @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class DateTime extends AbstractRule
  19. {
  20. use CanValidateDateTime;
  21. /**
  22. * @var string|null
  23. */
  24. private $format;
  25. /**
  26. * @var string
  27. */
  28. private $sample;
  29. /**
  30. * Initializes the rule.
  31. */
  32. public function __construct(?string $format = null)
  33. {
  34. $this->format = $format;
  35. $this->sample = date($format ?: 'c', strtotime('2005-12-30 01:02:03'));
  36. }
  37. /**
  38. * {@inheritDoc}
  39. */
  40. public function validate($input): bool
  41. {
  42. if ($input instanceof DateTimeInterface) {
  43. return $this->format === null;
  44. }
  45. if (!is_scalar($input)) {
  46. return false;
  47. }
  48. if ($this->format === null) {
  49. return strtotime((string) $input) !== false;
  50. }
  51. return $this->isDateTime($this->format, (string) $input);
  52. }
  53. }