Time.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 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 whether an input is a time or not
  17. *
  18. * @author Henrique Moody <henriquemoody@gmail.com>
  19. */
  20. final class Time extends AbstractRule
  21. {
  22. use CanValidateDateTime;
  23. /**
  24. * @var string
  25. */
  26. private $format;
  27. /**
  28. * @var string
  29. */
  30. private $sample;
  31. /**
  32. * Initializes the rule.
  33. *
  34. * @throws ComponentException
  35. */
  36. public function __construct(string $format = 'H:i:s')
  37. {
  38. if (!preg_match('/^[gGhHisuvaA\W]+$/', $format)) {
  39. throw new ComponentException(sprintf('"%s" is not a valid date format', $format));
  40. }
  41. $this->format = $format;
  42. $this->sample = date($format, strtotime('23:59:59'));
  43. }
  44. /**
  45. * {@inheritDoc}
  46. */
  47. public function validate($input): bool
  48. {
  49. if (!is_scalar($input)) {
  50. return false;
  51. }
  52. return $this->isDateTime($this->format, (string) $input);
  53. }
  54. }