3 namespace Drupal\Core\Entity;
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\RefinableCacheableDependencyTrait;
7 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
10 use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
11 use Drupal\Core\Language\Language;
12 use Drupal\Core\Language\LanguageInterface;
14 use Drupal\Core\Session\AccountInterface;
16 use Symfony\Component\Routing\Exception\RouteNotFoundException;
19 * Defines a base entity class.
21 abstract class Entity implements EntityInterface {
23 use RefinableCacheableDependencyTrait;
25 use DependencySerializationTrait {
26 __sleep as traitSleep;
34 protected $entityTypeId;
37 * Boolean indicating whether the entity should be forced to be new.
41 protected $enforceIsNew;
44 * A typed data object wrapping this entity.
46 * @var \Drupal\Core\TypedData\ComplexDataInterface
51 * Constructs an Entity object.
53 * @param array $values
54 * An array of values to set, keyed by property name. If the entity type
55 * has bundles, the bundle key has to be specified.
56 * @param string $entity_type
57 * The type of the entity to create.
59 public function __construct(array $values, $entity_type) {
60 $this->entityTypeId = $entity_type;
61 // Set initial values.
62 foreach ($values as $key => $value) {
68 * Gets the entity manager.
70 * @return \Drupal\Core\Entity\EntityManagerInterface
72 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
73 * Use \Drupal::entityTypeManager() instead in most cases. If the needed
74 * method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the
75 * deprecated \Drupal\Core\Entity\EntityManager to find the
76 * correct interface or service.
78 protected function entityManager() {
79 return \Drupal::entityManager();
83 * Gets the entity type manager.
85 * @return \Drupal\Core\Entity\EntityTypeManagerInterface
87 protected function entityTypeManager() {
88 return \Drupal::entityTypeManager();
92 * Gets the entity type bundle info service.
94 * @return \Drupal\Core\Entity\EntityTypeBundleInfoInterface
96 protected function entityTypeBundleInfo() {
97 return \Drupal::service('entity_type.bundle.info');
101 * Gets the language manager.
103 * @return \Drupal\Core\Language\LanguageManagerInterface
105 protected function languageManager() {
106 return \Drupal::languageManager();
110 * Gets the UUID generator.
112 * @return \Drupal\Component\Uuid\UuidInterface
114 protected function uuidGenerator() {
115 return \Drupal::service('uuid');
121 public function id() {
122 return isset($this->id) ? $this->id : NULL;
128 public function uuid() {
129 return isset($this->uuid) ? $this->uuid : NULL;
135 public function isNew() {
136 return !empty($this->enforceIsNew) || !$this->id();
142 public function enforceIsNew($value = TRUE) {
143 $this->enforceIsNew = $value;
151 public function getEntityTypeId() {
152 return $this->entityTypeId;
158 public function bundle() {
159 return $this->entityTypeId;
165 public function label() {
167 $entity_type = $this->getEntityType();
168 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
169 $label = call_user_func($label_callback, $this);
171 elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
172 $label = $this->{$label_key};
180 public function urlInfo($rel = 'canonical', array $options = []) {
181 return $this->toUrl($rel, $options);
187 public function toUrl($rel = 'canonical', array $options = []) {
188 if ($this->id() === NULL) {
189 throw new EntityMalformedException(sprintf('The "%s" entity cannot have a URI as it does not have an ID', $this->getEntityTypeId()));
192 // The links array might contain URI templates set in annotations.
193 $link_templates = $this->linkTemplates();
195 // Links pointing to the current revision point to the actual entity. So
196 // instead of using the 'revision' link, use the 'canonical' link.
197 if ($rel === 'revision' && $this instanceof RevisionableInterface && $this->isDefaultRevision()) {
201 if (isset($link_templates[$rel])) {
202 $route_parameters = $this->urlRouteParameters($rel);
203 $route_name = "entity.{$this->entityTypeId}." . str_replace(['-', 'drupal:'], ['_', ''], $rel);
204 $uri = new Url($route_name, $route_parameters);
207 $bundle = $this->bundle();
208 // A bundle-specific callback takes precedence over the generic one for
210 $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->getEntityTypeId());
211 if (isset($bundles[$bundle]['uri_callback'])) {
212 $uri_callback = $bundles[$bundle]['uri_callback'];
214 elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
215 $uri_callback = $entity_uri_callback;
218 // Invoke the callback to get the URI. If there is no callback, use the
219 // default URI format.
220 if (isset($uri_callback) && is_callable($uri_callback)) {
221 $uri = call_user_func($uri_callback, $this);
224 throw new UndefinedLinkTemplateException("No link template '$rel' found for the '{$this->getEntityTypeId()}' entity type");
228 // Pass the entity data through as options, so that alter functions do not
229 // need to look up this entity again.
231 ->setOption('entity_type', $this->getEntityTypeId())
232 ->setOption('entity', $this);
234 // Display links by default based on the current language.
235 // Link relations that do not require an existing entity should not be
236 // affected by this entity's language, however.
237 if (!in_array($rel, ['collection', 'add-page', 'add-form'], TRUE)) {
238 $options += ['language' => $this->language()];
241 $uri_options = $uri->getOptions();
242 $uri_options += $options;
244 return $uri->setOptions($uri_options);
250 public function hasLinkTemplate($rel) {
251 $link_templates = $this->linkTemplates();
252 return isset($link_templates[$rel]);
256 * Gets an array link templates.
259 * An array of link templates containing paths.
261 protected function linkTemplates() {
262 return $this->getEntityType()->getLinkTemplates();
268 public function link($text = NULL, $rel = 'canonical', array $options = []) {
269 return $this->toLink($text, $rel, $options)->toString();
275 public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
277 $text = $this->label();
279 $url = $this->toUrl($rel);
280 $options += $url->getOptions();
281 $url->setOptions($options);
282 return new Link($text, $url);
288 public function url($rel = 'canonical', $options = []) {
289 // While self::toUrl() will throw an exception if the entity has no id,
290 // the expected result for a URL is always a string.
291 if ($this->id() === NULL || !$this->hasLinkTemplate($rel)) {
295 $uri = $this->toUrl($rel);
296 $options += $uri->getOptions();
297 $uri->setOptions($options);
298 return $uri->toString();
302 * Gets an array of placeholders for this entity.
304 * Individual entity classes may override this method to add additional
305 * placeholders if desired. If so, they should be sure to replicate the
306 * property caching logic.
309 * The link relationship type, for example: canonical or edit-form.
312 * An array of URI placeholders.
314 protected function urlRouteParameters($rel) {
315 $uri_route_parameters = [];
317 if (!in_array($rel, ['collection', 'add-page', 'add-form'], TRUE)) {
318 // The entity ID is needed as a route parameter.
319 $uri_route_parameters[$this->getEntityTypeId()] = $this->id();
321 if ($rel === 'add-form' && ($this->getEntityType()->hasKey('bundle'))) {
322 $parameter_name = $this->getEntityType()->getBundleEntityType() ?: $this->getEntityType()->getKey('bundle');
323 $uri_route_parameters[$parameter_name] = $this->bundle();
325 if ($rel === 'revision' && $this instanceof RevisionableInterface) {
326 $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
329 return $uri_route_parameters;
335 public function uriRelationships() {
336 return array_filter(array_keys($this->linkTemplates()), function ($link_relation_type) {
337 // It's not guaranteed that every link relation type also has a
338 // corresponding route. For some, additional modules or configuration may
339 // be necessary. The interface demands that we only return supported URI
342 $this->toUrl($link_relation_type)->toString(TRUE)->getGeneratedUrl();
344 catch (RouteNotFoundException $e) {
354 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
355 if ($operation == 'create') {
356 return $this->entityTypeManager()
357 ->getAccessControlHandler($this->entityTypeId)
358 ->createAccess($this->bundle(), $account, [], $return_as_object);
360 return $this->entityTypeManager()
361 ->getAccessControlHandler($this->entityTypeId)
362 ->access($this, $operation, $account, $return_as_object);
368 public function language() {
369 if ($key = $this->getEntityType()->getKey('langcode')) {
370 $langcode = $this->$key;
371 $language = $this->languageManager()->getLanguage($langcode);
376 // Make sure we return a proper language object.
377 $langcode = !empty($this->langcode) ? $this->langcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
378 $language = new Language(['id' => $langcode]);
385 public function save() {
386 $storage = $this->entityTypeManager()->getStorage($this->entityTypeId);
387 return $storage->save($this);
393 public function delete() {
394 if (!$this->isNew()) {
395 $this->entityTypeManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
402 public function createDuplicate() {
403 $duplicate = clone $this;
404 $entity_type = $this->getEntityType();
405 // Reset the entity ID and indicate that this is a new entity.
406 $duplicate->{$entity_type->getKey('id')} = NULL;
407 $duplicate->enforceIsNew();
409 // Check if the entity type supports UUIDs and generate a new one if so.
410 if ($entity_type->hasKey('uuid')) {
411 $duplicate->{$entity_type->getKey('uuid')} = $this->uuidGenerator()->generate();
419 public function getEntityType() {
420 return $this->entityTypeManager()->getDefinition($this->getEntityTypeId());
426 public function preSave(EntityStorageInterface $storage) {
427 // Check if this is an entity bundle.
428 if ($this->getEntityType()->getBundleOf()) {
429 // Throw an exception if the bundle ID is longer than 32 characters.
430 if (Unicode::strlen($this->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
431 throw new ConfigEntityIdLengthException("Attempt to create a bundle with an ID longer than " . EntityTypeInterface::BUNDLE_MAX_LENGTH . " characters: $this->id().");
439 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
440 $this->invalidateTagsOnSave($update);
446 public static function preCreate(EntityStorageInterface $storage, array &$values) {
452 public function postCreate(EntityStorageInterface $storage) {
458 public static function preDelete(EntityStorageInterface $storage, array $entities) {
464 public static function postDelete(EntityStorageInterface $storage, array $entities) {
465 static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
471 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
477 public function referencedEntities() {
484 public function getCacheContexts() {
485 return $this->cacheContexts;
491 public function getCacheTagsToInvalidate() {
492 // @todo Add bundle-specific listing cache tag?
493 // https://www.drupal.org/node/2145751
494 if ($this->isNew()) {
497 return [$this->entityTypeId . ':' . $this->id()];
503 public function getCacheTags() {
504 if ($this->cacheTags) {
505 return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
507 return $this->getCacheTagsToInvalidate();
513 public function getCacheMaxAge() {
514 return $this->cacheMaxAge;
520 public static function load($id) {
521 $entity_type_repository = \Drupal::service('entity_type.repository');
522 $entity_type_manager = \Drupal::entityTypeManager();
523 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
524 return $storage->load($id);
530 public static function loadMultiple(array $ids = NULL) {
531 $entity_type_repository = \Drupal::service('entity_type.repository');
532 $entity_type_manager = \Drupal::entityTypeManager();
533 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
534 return $storage->loadMultiple($ids);
540 public static function create(array $values = []) {
541 $entity_type_repository = \Drupal::service('entity_type.repository');
542 $entity_type_manager = \Drupal::entityTypeManager();
543 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
544 return $storage->create($values);
548 * Invalidates an entity's cache tags upon save.
550 * @param bool $update
551 * TRUE if the entity has been updated, or FALSE if it has been inserted.
553 protected function invalidateTagsOnSave($update) {
554 // An entity was created or updated: invalidate its list cache tags. (An
555 // updated entity may start to appear in a listing because it now meets that
556 // listing's filtering requirements. A newly created entity may start to
557 // appear in listings because it did not exist before.)
558 $tags = $this->getEntityType()->getListCacheTags();
559 if ($this->hasLinkTemplate('canonical')) {
560 // Creating or updating an entity may change a cached 403 or 404 response.
561 $tags = Cache::mergeTags($tags, ['4xx-response']);
564 // An existing entity was updated, also invalidate its unique cache tag.
565 $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
567 Cache::invalidateTags($tags);
571 * Invalidates an entity's cache tags upon delete.
573 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
574 * The entity type definition.
575 * @param \Drupal\Core\Entity\EntityInterface[] $entities
576 * An array of entities.
578 protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
579 $tags = $entity_type->getListCacheTags();
580 foreach ($entities as $entity) {
581 // An entity was deleted: invalidate its own cache tag, but also its list
582 // cache tags. (A deleted entity may cause changes in a paged list on
583 // other pages than the one it's on. The one it's on is handled by its own
584 // cache tag, but subsequent list pages would not be invalidated, hence we
585 // must invalidate its list cache tags as well.)
586 $tags = Cache::mergeTags($tags, $entity->getCacheTagsToInvalidate());
588 Cache::invalidateTags($tags);
594 public function getOriginalId() {
595 // By default, entities do not support renames and do not have original IDs.
602 public function setOriginalId($id) {
603 // By default, entities do not support renames and do not have original IDs.
604 // If the specified ID is anything except NULL, this should mark this entity
607 $this->enforceIsNew(FALSE);
616 public function toArray() {
623 public function getTypedData() {
624 if (!isset($this->typedData)) {
625 $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
626 $this->typedData = $class::createFromEntity($this);
628 return $this->typedData;
634 public function __sleep() {
635 $this->typedData = NULL;
636 return $this->traitSleep();
642 public function getConfigDependencyKey() {
643 return $this->getEntityType()->getConfigDependencyKey();
649 public function getConfigDependencyName() {
650 return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
656 public function getConfigTarget() {
657 // For content entities, use the UUID for the config target identifier.
658 // This ensures that references to the target can be deployed reliably.
659 return $this->uuid();