Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Validator\Constraints; Chris@0: Chris@0: use Symfony\Component\Validator\Constraint; Chris@0: use Symfony\Component\Validator\ConstraintValidator; Chris@0: use Symfony\Component\Validator\Exception\UnexpectedTypeException; Chris@0: Chris@0: /** Chris@0: * @author Bernhard Schussek Chris@0: */ Chris@0: class TimeValidator extends ConstraintValidator Chris@0: { Chris@0: const PATTERN = '/^(\d{2}):(\d{2}):(\d{2})$/'; Chris@0: Chris@0: /** Chris@0: * Checks whether a time is valid. Chris@0: * Chris@0: * @param int $hour The hour Chris@0: * @param int $minute The minute Chris@0: * @param int $second The second Chris@0: * Chris@0: * @return bool Whether the time is valid Chris@0: * Chris@0: * @internal Chris@0: */ Chris@0: public static function checkTime($hour, $minute, $second) Chris@0: { Chris@0: return $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60 && $second >= 0 && $second < 60; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function validate($value, Constraint $constraint) Chris@0: { Chris@0: if (!$constraint instanceof Time) { Chris@0: throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Time'); Chris@0: } Chris@0: Chris@14: if (null === $value || '' === $value || $value instanceof \DateTimeInterface) { Chris@0: return; Chris@0: } Chris@0: Chris@17: if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { Chris@0: throw new UnexpectedTypeException($value, 'string'); Chris@0: } Chris@0: Chris@0: $value = (string) $value; Chris@0: Chris@0: if (!preg_match(static::PATTERN, $value, $matches)) { Chris@0: $this->context->buildViolation($constraint->message) Chris@0: ->setParameter('{{ value }}', $this->formatValue($value)) Chris@0: ->setCode(Time::INVALID_FORMAT_ERROR) Chris@0: ->addViolation(); Chris@0: Chris@0: return; Chris@0: } Chris@0: Chris@0: if (!self::checkTime($matches[1], $matches[2], $matches[3])) { Chris@0: $this->context->buildViolation($constraint->message) Chris@0: ->setParameter('{{ value }}', $this->formatValue($value)) Chris@0: ->setCode(Time::INVALID_TIME_ERROR) Chris@0: ->addViolation(); Chris@0: } Chris@0: } Chris@0: }