EntityPublishedTrait.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. $key = $this->getEntityType()->getKey('published');
  43. return (bool) $this->get($key)->value;
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function setPublished($published = NULL) {
  49. if ($published !== NULL) {
  50. @trigger_error('The $published parameter is deprecated since version 8.3.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
  51. $value = (bool) $published;
  52. }
  53. else {
  54. $value = TRUE;
  55. }
  56. $key = $this->getEntityType()->getKey('published');
  57. $this->set($key, $value);
  58. return $this;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function setUnpublished() {
  64. $key = $this->getEntityType()->getKey('published');
  65. $this->set($key, FALSE);
  66. return $this;
  67. }
  68. }