EntityPublishedTrait.php 2.32 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Entity;

5
use Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Provides a trait for published status.
 */
trait EntityPublishedTrait {

  /**
   * Returns an array of base field definitions for publishing status.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type to add the publishing status field to.
   *
   * @return \Drupal\Core\Field\BaseFieldDefinition[]
21 22 23 24 25
   *   An array of base field definitions.
   *
   * @throws \Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException
   *   Thrown when the entity type does not implement EntityPublishedInterface
   *   or if it does not have a "published" entity key.
26 27
   */
  public static function publishedBaseFieldDefinitions(EntityTypeInterface $entity_type) {
28 29 30 31 32 33 34
    if (!is_subclass_of($entity_type->getClass(), EntityPublishedInterface::class)) {
      throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not implement \Drupal\Core\Entity\EntityPublishedInterface.');
    }
    if (!$entity_type->hasKey('published')) {
      throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not have a "published" entity key.');
    }

35 36 37 38 39 40 41
    return [
      $entity_type->getKey('published') => BaseFieldDefinition::create('boolean')
        ->setLabel(new TranslatableMarkup('Published'))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE)
        ->setDefaultValue(TRUE),
    ];
42 43 44
  }

  /**
45
   * {@inheritdoc}
46 47
   */
  public function isPublished() {
48
    return (bool) $this->getEntityKey('published');
49 50 51
  }

  /**
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
   * {@inheritdoc}
   */
  public function setPublished($published = NULL) {
    if ($published !== NULL) {
      @trigger_error('The $published parameter is deprecated since version 8.3.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
      $value = (bool) $published;
    }
    else {
      $value = TRUE;
    }
    $key = $this->getEntityType()->getKey('published');
    $this->set($key, $value);

    return $this;
  }

  /**
   * {@inheritdoc}
70
   */
71 72 73 74
  public function setUnpublished() {
    $key = $this->getEntityType()->getKey('published');
    $this->set($key, FALSE);

75 76 77 78
    return $this;
  }

}