EntityOwnerTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Drupal\user;
  3. use Drupal\Core\Entity\EntityTypeInterface;
  4. use Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException;
  5. use Drupal\Core\Field\BaseFieldDefinition;
  6. use Drupal\Core\StringTranslation\TranslatableMarkup;
  7. /**
  8. * Provides a trait for entities that have an owner.
  9. */
  10. trait EntityOwnerTrait {
  11. /**
  12. * Returns an array of base field definitions for entity owners.
  13. *
  14. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  15. * The entity type to add the owner field to.
  16. *
  17. * @return \Drupal\Core\Field\BaseFieldDefinition[]
  18. * An array of base field definitions.
  19. *
  20. * @throws \Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException
  21. * Thrown when the entity type does not implement EntityOwnerInterface or
  22. * if it does not have an "owner" entity key.
  23. */
  24. public static function ownerBaseFieldDefinitions(EntityTypeInterface $entity_type) {
  25. if (!is_subclass_of($entity_type->getClass(), EntityOwnerInterface::class)) {
  26. throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not implement \Drupal\user\EntityOwnerInterface.');
  27. }
  28. if (!$entity_type->hasKey('owner')) {
  29. throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not have an "owner" entity key.');
  30. }
  31. return [
  32. $entity_type->getKey('owner') => BaseFieldDefinition::create('entity_reference')
  33. ->setLabel(new TranslatableMarkup('User ID'))
  34. ->setSetting('target_type', 'user')
  35. ->setTranslatable($entity_type->isTranslatable())
  36. ->setDefaultValueCallback(static::class . '::getDefaultEntityOwner'),
  37. ];
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function getOwnerId() {
  43. return $this->getEntityKey('owner');
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function setOwnerId($uid) {
  49. $key = $this->getEntityType()->getKey('owner');
  50. $this->set($key, $uid);
  51. return $this;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function getOwner() {
  57. $key = $this->getEntityType()->getKey('owner');
  58. return $this->get($key)->entity;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function setOwner(UserInterface $account) {
  64. $key = $this->getEntityType()->getKey('owner');
  65. $this->set($key, $account);
  66. return $this;
  67. }
  68. /**
  69. * Default value callback for 'owner' base field.
  70. *
  71. * @return mixed
  72. * A default value for the owner field.
  73. */
  74. public static function getDefaultEntityOwner() {
  75. return \Drupal::currentUser()->id();
  76. }
  77. }