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\Exception\UnexpectedTypeException;
18 * @author Bernhard Schussek <bschussek@gmail.com>
19 * @author Diego Saint Esteben <diego@saintesteben.me>
21 class DateTimeValidator extends DateValidator
24 * @deprecated since version 3.1, to be removed in 4.0.
26 const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/';
31 public function validate($value, Constraint $constraint)
33 if (!$constraint instanceof DateTime) {
34 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\DateTime');
37 if (null === $value || '' === $value || $value instanceof \DateTimeInterface) {
41 if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
42 throw new UnexpectedTypeException($value, 'string');
45 $value = (string) $value;
47 \DateTime::createFromFormat($constraint->format, $value);
49 $errors = \DateTime::getLastErrors();
51 if (0 < $errors['error_count']) {
52 $this->context->buildViolation($constraint->message)
53 ->setParameter('{{ value }}', $this->formatValue($value))
54 ->setCode(DateTime::INVALID_FORMAT_ERROR)
60 foreach ($errors['warnings'] as $warning) {
61 if ('The parsed date was invalid' === $warning) {
62 $this->context->buildViolation($constraint->message)
63 ->setParameter('{{ value }}', $this->formatValue($value))
64 ->setCode(DateTime::INVALID_DATE_ERROR)
66 } elseif ('The parsed time was invalid' === $warning) {
67 $this->context->buildViolation($constraint->message)
68 ->setParameter('{{ value }}', $this->formatValue($value))
69 ->setCode(DateTime::INVALID_TIME_ERROR)
72 $this->context->buildViolation($constraint->message)
73 ->setParameter('{{ value }}', $this->formatValue($value))
74 ->setCode(DateTime::INVALID_FORMAT_ERROR)