DateTimeDayComputed.php in Date time day 8
File
src/DateTimeDayComputed.php
View source
<?php
namespace Drupal\date_time_day;
use Drupal\date_time_day\Plugin\Field\FieldType\DateTimeDayItem;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\Core\TypedData\TypedData;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
class DateTimeDayComputed extends TypedData {
protected $date = NULL;
public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
parent::__construct($definition, $name, $parent);
if (!$definition
->getSetting('date source')) {
throw new \InvalidArgumentException("The definition's 'date source' key has to specify the name of the date time property to be computed.");
}
}
public function getValue($langcode = NULL) {
if ($this->date !== NULL) {
return $this->date;
}
$item = $this
->getParent();
$value = $item->{$this->definition
->getSetting('date source')};
$datetime_type = $item
->getFieldDefinition()
->getSetting('time_type');
$storage_format = $datetime_type === DateTimeDayItem::DATEDAY_TIME_DEFAULT_TYPE_FORMAT ? DateTimeDayItem::DATE_TIME_DAY_H_I_FORMAT_STORAGE_FORMAT : DateTimeDayItem::DATE_TIME_DAY_H_I_S_FORMAT_STORAGE_FORMAT;
if ($datetime_type === DateTimeDayItem::DATEDAY_TIME_TYPE_SECONDS_FORMAT && strlen($value) === 5) {
$value = "{$value}:00";
}
try {
$date = DrupalDateTime::createFromFormat($storage_format, $value, DateTimeItemInterface::STORAGE_TIMEZONE);
if ($date instanceof DrupalDateTime && !$date
->hasErrors()) {
$this->date = $date;
}
} catch (\Exception $e) {
}
return $this->date;
}
public function setValue($value, $notify = TRUE) {
$this->date = $value;
if ($notify && isset($this->parent)) {
$this->parent
->onChange($this->name);
}
}
}