a027a82f098491661522a29d197a15be53777437
[yaffs-website] / web / core / modules / datetime / src / Plugin / Validation / Constraint / DateTimeFormatConstraintValidator.php
1 <?php
2
3 namespace Drupal\datetime\Plugin\Validation\Constraint;
4
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;
9
10 /**
11  * Constraint validator for DateTime items to ensure the format is correct.
12  */
13 class DateTimeFormatConstraintValidator extends ConstraintValidator {
14
15   /**
16    * {@inheritdoc}
17    */
18   public function validate($item, Constraint $constraint) {
19     /* @var $item \Drupal\datetime\Plugin\Field\FieldType\DateTimeItem */
20     if (isset($item)) {
21       $value = $item->getValue()['value'];
22       if (!is_string($value)) {
23         $this->context->addViolation($constraint->badType);
24       }
25       else {
26         $datetime_type = $item->getFieldDefinition()->getSetting('datetime_type');
27         $format = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE ? DATETIME_DATE_STORAGE_FORMAT : DATETIME_DATETIME_STORAGE_FORMAT;
28         $date = NULL;
29         try {
30           $date = DateTimePlus::createFromFormat($format, $value, new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
31         }
32         catch (\InvalidArgumentException $e) {
33           $this->context->addViolation($constraint->badFormat, [
34             '@value' => $value,
35             '@format' => $format,
36           ]);
37           return;
38         }
39         catch (\UnexpectedValueException $e) {
40           $this->context->addViolation($constraint->badValue, [
41             '@value' => $value,
42             '@format' => $format,
43           ]);
44           return;
45         }
46         if ($date === NULL || $date->hasErrors()) {
47           $this->context->addViolation($constraint->badFormat, [
48             '@value' => $value,
49             '@format' => $format,
50           ]);
51         }
52       }
53     }
54   }
55
56 }