4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class TimeValidator extends ConstraintValidator
23 const PATTERN = '/^(\d{2}):(\d{2}):(\d{2})$/';
26 * Checks whether a time is valid.
28 * @param int $hour The hour
29 * @param int $minute The minute
30 * @param int $second The second
32 * @return bool Whether the time is valid
36 public static function checkTime($hour, $minute, $second)
38 return $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60 && $second >= 0 && $second < 60;
44 public function validate($value, Constraint $constraint)
46 if (!$constraint instanceof Time) {
47 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Time');
50 if (null === $value || '' === $value || $value instanceof \DateTimeInterface) {
54 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
55 throw new UnexpectedTypeException($value, 'string');
58 $value = (string) $value;
60 if (!preg_match(static::PATTERN, $value, $matches)) {
61 $this->context->buildViolation($constraint->message)
62 ->setParameter('{{ value }}', $this->formatValue($value))
63 ->setCode(Time::INVALID_FORMAT_ERROR)
69 if (!self::checkTime($matches[1], $matches[2], $matches[3])) {
70 $this->context->buildViolation($constraint->message)
71 ->setParameter('{{ value }}', $this->formatValue($value))
72 ->setCode(Time::INVALID_TIME_ERROR)