PublicationDateItem.php in Publication Date 8
File
src/Plugin/Field/FieldType/PublicationDateItem.php
View source
<?php
namespace Drupal\publication_date\Plugin\Field\FieldType;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem;
use Drupal\Core\TypedData\DataDefinition;
class PublicationDateItem extends ChangedItem {
public function applyDefaultValue($notify = TRUE) {
$value = $this
->isPublished() ? REQUEST_TIME : NULL;
$published_at_or_now = isset($value) ? $value : REQUEST_TIME;
$this
->setValue([
'value' => $value,
'published_at_or_now' => $published_at_or_now,
], $notify);
return $this;
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = parent::propertyDefinitions($field_definition);
$properties['published_at_or_now'] = DataDefinition::create('timestamp')
->setLabel(t('Published at or now'))
->setComputed(TRUE);
return $properties;
}
public function preSave() {
if (!$this
->isPublished() && !$this->value) {
$this->value = PUBLICATION_DATE_DEFAULT;
}
if (!$this->value) {
$this->value = REQUEST_TIME;
}
}
protected function isPublished() {
$entity = $this
->getEntity();
if (!($entity instanceof FieldableEntityInterface && $entity
->hasField('status'))) {
return FALSE;
}
return $entity
->get('status')->value;
}
public function isEmpty() {
if (isset($this->value) || isset($this->published_at_or_now)) {
return FALSE;
}
return TRUE;
}
}