EntityPublishedTrait.php 2.3 KB

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