Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Entity / EntityPublishedTrait.php
1 <?php
2
3 namespace Drupal\Core\Entity;
4
5 use Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException;
6 use Drupal\Core\Field\BaseFieldDefinition;
7 use Drupal\Core\StringTranslation\TranslatableMarkup;
8
9 /**
10  * Provides a trait for published status.
11  */
12 trait EntityPublishedTrait {
13
14   /**
15    * Returns an array of base field definitions for publishing status.
16    *
17    * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
18    *   The entity type to add the publishing status field to.
19    *
20    * @return \Drupal\Core\Field\BaseFieldDefinition[]
21    *   An array of base field definitions.
22    *
23    * @throws \Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException
24    *   Thrown when the entity type does not implement EntityPublishedInterface
25    *   or if it does not have a "published" entity key.
26    */
27   public static function publishedBaseFieldDefinitions(EntityTypeInterface $entity_type) {
28     if (!is_subclass_of($entity_type->getClass(), EntityPublishedInterface::class)) {
29       throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not implement \Drupal\Core\Entity\EntityPublishedInterface.');
30     }
31     if (!$entity_type->hasKey('published')) {
32       throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not have a "published" entity key.');
33     }
34
35     return [$entity_type->getKey('published') => BaseFieldDefinition::create('boolean')
36       ->setLabel(new TranslatableMarkup('Publishing status'))
37       ->setDescription(new TranslatableMarkup('A boolean indicating the published state.'))
38       ->setRevisionable(TRUE)
39       ->setTranslatable(TRUE)
40       ->setDefaultValue(TRUE)];
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public function isPublished() {
47     $key = $this->getEntityType()->getKey('published');
48     return (bool) $this->get($key)->value;
49   }
50
51   /**
52    * {@inheritdoc}
53    */
54   public function setPublished($published = NULL) {
55     if ($published !== NULL) {
56       @trigger_error('The $published parameter is deprecated since version 8.3.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
57       $value = (bool) $published;
58     }
59     else {
60       $value = TRUE;
61     }
62     $key = $this->getEntityType()->getKey('published');
63     $this->set($key, $value);
64
65     return $this;
66   }
67
68   /**
69    * {@inheritdoc}
70    */
71   public function setUnpublished() {
72     $key = $this->getEntityType()->getKey('published');
73     $this->set($key, FALSE);
74
75     return $this;
76   }
77
78 }