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\Context\ExecutionContextInterface;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class DateTimeValidator extends DateValidator
23 const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/';
28 public function validate($value, Constraint $constraint)
30 if (!$constraint instanceof DateTime) {
31 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\DateTime');
34 if (null === $value || '' === $value || $value instanceof \DateTime) {
38 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
39 throw new UnexpectedTypeException($value, 'string');
42 $value = (string) $value;
44 if (!preg_match(static::PATTERN, $value, $matches)) {
45 if ($this->context instanceof ExecutionContextInterface) {
46 $this->context->buildViolation($constraint->message)
47 ->setParameter('{{ value }}', $this->formatValue($value))
48 ->setCode(DateTime::INVALID_FORMAT_ERROR)
51 $this->buildViolation($constraint->message)
52 ->setParameter('{{ value }}', $this->formatValue($value))
53 ->setCode(DateTime::INVALID_FORMAT_ERROR)
60 if (!DateValidator::checkDate($matches[1], $matches[2], $matches[3])) {
61 if ($this->context instanceof ExecutionContextInterface) {
62 $this->context->buildViolation($constraint->message)
63 ->setParameter('{{ value }}', $this->formatValue($value))
64 ->setCode(DateTime::INVALID_DATE_ERROR)
67 $this->buildViolation($constraint->message)
68 ->setParameter('{{ value }}', $this->formatValue($value))
69 ->setCode(DateTime::INVALID_DATE_ERROR)
74 if (!TimeValidator::checkTime($matches[4], $matches[5], $matches[6])) {
75 if ($this->context instanceof ExecutionContextInterface) {
76 $this->context->buildViolation($constraint->message)
77 ->setParameter('{{ value }}', $this->formatValue($value))
78 ->setCode(DateTime::INVALID_TIME_ERROR)
81 $this->buildViolation($constraint->message)
82 ->setParameter('{{ value }}', $this->formatValue($value))
83 ->setCode(DateTime::INVALID_TIME_ERROR)