TimeValidator.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 TimeValidator extends ConstraintValidator
  19. {
  20. public const PATTERN = '/^(\d{2}):(\d{2}):(\d{2})$/';
  21. /**
  22. * Checks whether a time is valid.
  23. *
  24. * @internal
  25. */
  26. public static function checkTime(int $hour, int $minute, float $second): bool
  27. {
  28. return $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60 && $second >= 0 && $second < 60;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function validate($value, Constraint $constraint)
  34. {
  35. if (!$constraint instanceof Time) {
  36. throw new UnexpectedTypeException($constraint, Time::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(Time::INVALID_FORMAT_ERROR)
  49. ->addViolation();
  50. return;
  51. }
  52. if (!self::checkTime($matches[1], $matches[2], $matches[3])) {
  53. $this->context->buildViolation($constraint->message)
  54. ->setParameter('{{ value }}', $this->formatValue($value))
  55. ->setCode(Time::INVALID_TIME_ERROR)
  56. ->addViolation();
  57. }
  58. }
  59. }