LeapDate.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 DateTimeImmutable;
  9. use DateTimeInterface;
  10. use function is_scalar;
  11. /**
  12. * Validates if a date is leap.
  13. *
  14. * @author Danilo Benevides <danilobenevides01@gmail.com>
  15. * @author Henrique Moody <henriquemoody@gmail.com>
  16. * @author Jayson Reis <santosdosreis@gmail.com>
  17. */
  18. final class LeapDate extends AbstractRule
  19. {
  20. /**
  21. * @var string
  22. */
  23. private $format;
  24. /**
  25. * Initializes the rule with the expected format.
  26. */
  27. public function __construct(string $format)
  28. {
  29. $this->format = $format;
  30. }
  31. /**
  32. * {@inheritDoc}
  33. */
  34. public function validate($input): bool
  35. {
  36. if ($input instanceof DateTimeInterface) {
  37. return $input->format('m-d') === '02-29';
  38. }
  39. if (is_scalar($input)) {
  40. return $this->validate(DateTimeImmutable::createFromFormat($this->format, (string) $input));
  41. }
  42. return false;
  43. }
  44. }