3 namespace Drupal\datetime;
5 use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
6 use Drupal\Core\Datetime\DrupalDateTime;
7 use Drupal\Core\TypedData\DataDefinitionInterface;
8 use Drupal\Core\TypedData\TypedDataInterface;
9 use Drupal\Core\TypedData\TypedData;
12 * A computed property for dates of date time field items.
14 * Required settings (below the definition's 'settings' key) are:
15 * - date source: The date property containing the to be computed date.
17 class DateTimeComputed extends TypedData {
20 * Cached computed date.
24 protected $date = NULL;
29 public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
30 parent::__construct($definition, $name, $parent);
31 if (!$definition->getSetting('date source')) {
32 throw new \InvalidArgumentException("The definition's 'date source' key has to specify the name of the date property to be computed.");
39 public function getValue($langcode = NULL) {
40 if ($this->date !== NULL) {
44 /** @var \Drupal\Core\Field\FieldItemInterface $item */
45 $item = $this->getParent();
46 $value = $item->{($this->definition->getSetting('date source'))};
48 $datetime_type = $item->getFieldDefinition()->getSetting('datetime_type');
49 $storage_format = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE ? DATETIME_DATE_STORAGE_FORMAT : DATETIME_DATETIME_STORAGE_FORMAT;
51 $date = DrupalDateTime::createFromFormat($storage_format, $value, DATETIME_STORAGE_TIMEZONE);
52 if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
54 // If the format did not include an explicit time portion, then the
55 // time will be set from the current time instead. For consistency, we
56 // set the time to 12:00:00 UTC for date-only fields. This is used so
57 // that the local date portion is the same, across nearly all time
59 // @see datetime_date_default_time()
60 // @see http://php.net/manual/en/datetime.createfromformat.php
61 // @todo Update comment and/or code per the chosen solution in
62 // https://www.drupal.org/node/2830094
63 if ($datetime_type === DateTimeItem::DATETIME_TYPE_DATE) {
64 $this->date->setTime(12, 0, 0);
68 catch (\Exception $e) {
77 public function setValue($value, $notify = TRUE) {
79 // Notify the parent of any changes.
80 if ($notify && isset($this->parent)) {
81 $this->parent->onChange($this->name);