3 namespace Drupal\datetime\Plugin\Validation\Constraint;
5 use Drupal\Component\Datetime\DateTimePlus;
6 use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
7 use Symfony\Component\Validator\Constraint;
8 use Symfony\Component\Validator\ConstraintValidator;
11 * Constraint validator for DateTime items to ensure the format is correct.
13 class DateTimeFormatConstraintValidator extends ConstraintValidator {
18 public function validate($item, Constraint $constraint) {
19 /* @var $item \Drupal\datetime\Plugin\Field\FieldType\DateTimeItem */
21 $value = $item->getValue()['value'];
22 if (!is_string($value)) {
23 $this->context->addViolation($constraint->badType);
26 $datetime_type = $item->getFieldDefinition()->getSetting('datetime_type');
27 $format = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE ? DATETIME_DATE_STORAGE_FORMAT : DATETIME_DATETIME_STORAGE_FORMAT;
30 $date = DateTimePlus::createFromFormat($format, $value, new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
32 catch (\InvalidArgumentException $e) {
33 $this->context->addViolation($constraint->badFormat, [
39 catch (\UnexpectedValueException $e) {
40 $this->context->addViolation($constraint->badValue, [
46 if ($date === NULL || $date->hasErrors()) {
47 $this->context->addViolation($constraint->badFormat, [