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;
10 use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
13 * A computed property for dates of date time field items.
15 * Required settings (below the definition's 'settings' key) are:
16 * - date source: The date property containing the to be computed date.
18 class DateTimeComputed extends TypedData {
21 * Cached computed date.
25 protected $date = NULL;
30 public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
31 parent::__construct($definition, $name, $parent);
32 if (!$definition->getSetting('date source')) {
33 throw new \InvalidArgumentException("The definition's 'date source' key has to specify the name of the date property to be computed.");
40 public function getValue() {
41 if ($this->date !== NULL) {
45 /** @var \Drupal\Core\Field\FieldItemInterface $item */
46 $item = $this->getParent();
47 $value = $item->{($this->definition->getSetting('date source'))};
49 $datetime_type = $item->getFieldDefinition()->getSetting('datetime_type');
50 $storage_format = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
52 $date = DrupalDateTime::createFromFormat($storage_format, $value, DateTimeItemInterface::STORAGE_TIMEZONE);
53 if ($date instanceof DrupalDateTime && !$date->hasErrors()) {
55 // If the format did not include an explicit time portion, then the
56 // time will be set from the current time instead. For consistency, we
57 // set the time to 12:00:00 UTC for date-only fields. This is used so
58 // that the local date portion is the same, across nearly all time
60 // @see \Drupal\Component\Datetime\DateTimePlus::setDefaultDateTime()
61 // @see http://php.net/manual/datetime.createfromformat.php
62 if ($datetime_type === DateTimeItem::DATETIME_TYPE_DATE) {
63 $this->date->setDefaultDateTime();
67 catch (\Exception $e) {
76 public function setValue($value, $notify = TRUE) {
78 // Notify the parent of any changes.
79 if ($notify && isset($this->parent)) {
80 $this->parent->onChange($this->name);