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\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
9 use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
10 use Drupal\Core\Language\Language;
11 use Drupal\Core\Language\LanguageInterface;
13 use Drupal\Core\Session\AccountInterface;
15 use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
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) {
347 catch (MissingMandatoryParametersException $e) {
357 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
358 if ($operation == 'create') {
359 return $this->entityTypeManager()
360 ->getAccessControlHandler($this->entityTypeId)
361 ->createAccess($this->bundle(), $account, [], $return_as_object);
363 return $this->entityTypeManager()
364 ->getAccessControlHandler($this->entityTypeId)
365 ->access($this, $operation, $account, $return_as_object);
371 public function language() {
372 if ($key = $this->getEntityType()->getKey('langcode')) {
373 $langcode = $this->$key;
374 $language = $this->languageManager()->getLanguage($langcode);
379 // Make sure we return a proper language object.
380 $langcode = !empty($this->langcode) ? $this->langcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
381 $language = new Language(['id' => $langcode]);
388 public function save() {
389 $storage = $this->entityTypeManager()->getStorage($this->entityTypeId);
390 return $storage->save($this);
396 public function delete() {
397 if (!$this->isNew()) {
398 $this->entityTypeManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
405 public function createDuplicate() {
406 $duplicate = clone $this;
407 $entity_type = $this->getEntityType();
408 // Reset the entity ID and indicate that this is a new entity.
409 $duplicate->{$entity_type->getKey('id')} = NULL;
410 $duplicate->enforceIsNew();
412 // Check if the entity type supports UUIDs and generate a new one if so.
413 if ($entity_type->hasKey('uuid')) {
414 $duplicate->{$entity_type->getKey('uuid')} = $this->uuidGenerator()->generate();
422 public function getEntityType() {
423 return $this->entityTypeManager()->getDefinition($this->getEntityTypeId());
429 public function preSave(EntityStorageInterface $storage) {
430 // Check if this is an entity bundle.
431 if ($this->getEntityType()->getBundleOf()) {
432 // Throw an exception if the bundle ID is longer than 32 characters.
433 if (mb_strlen($this->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
434 throw new ConfigEntityIdLengthException("Attempt to create a bundle with an ID longer than " . EntityTypeInterface::BUNDLE_MAX_LENGTH . " characters: $this->id().");
442 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
443 $this->invalidateTagsOnSave($update);
449 public static function preCreate(EntityStorageInterface $storage, array &$values) {
455 public function postCreate(EntityStorageInterface $storage) {
461 public static function preDelete(EntityStorageInterface $storage, array $entities) {
467 public static function postDelete(EntityStorageInterface $storage, array $entities) {
468 static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
474 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
480 public function referencedEntities() {
487 public function getCacheContexts() {
488 return $this->cacheContexts;
494 public function getCacheTagsToInvalidate() {
495 // @todo Add bundle-specific listing cache tag?
496 // https://www.drupal.org/node/2145751
497 if ($this->isNew()) {
500 return [$this->entityTypeId . ':' . $this->id()];
506 public function getCacheTags() {
507 if ($this->cacheTags) {
508 return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
510 return $this->getCacheTagsToInvalidate();
516 public function getCacheMaxAge() {
517 return $this->cacheMaxAge;
523 public static function load($id) {
524 $entity_type_repository = \Drupal::service('entity_type.repository');
525 $entity_type_manager = \Drupal::entityTypeManager();
526 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
527 return $storage->load($id);
533 public static function loadMultiple(array $ids = NULL) {
534 $entity_type_repository = \Drupal::service('entity_type.repository');
535 $entity_type_manager = \Drupal::entityTypeManager();
536 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
537 return $storage->loadMultiple($ids);
543 public static function create(array $values = []) {
544 $entity_type_repository = \Drupal::service('entity_type.repository');
545 $entity_type_manager = \Drupal::entityTypeManager();
546 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
547 return $storage->create($values);
551 * Invalidates an entity's cache tags upon save.
553 * @param bool $update
554 * TRUE if the entity has been updated, or FALSE if it has been inserted.
556 protected function invalidateTagsOnSave($update) {
557 // An entity was created or updated: invalidate its list cache tags. (An
558 // updated entity may start to appear in a listing because it now meets that
559 // listing's filtering requirements. A newly created entity may start to
560 // appear in listings because it did not exist before.)
561 $tags = $this->getEntityType()->getListCacheTags();
562 if ($this->hasLinkTemplate('canonical')) {
563 // Creating or updating an entity may change a cached 403 or 404 response.
564 $tags = Cache::mergeTags($tags, ['4xx-response']);
567 // An existing entity was updated, also invalidate its unique cache tag.
568 $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
570 Cache::invalidateTags($tags);
574 * Invalidates an entity's cache tags upon delete.
576 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
577 * The entity type definition.
578 * @param \Drupal\Core\Entity\EntityInterface[] $entities
579 * An array of entities.
581 protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
582 $tags = $entity_type->getListCacheTags();
583 foreach ($entities as $entity) {
584 // An entity was deleted: invalidate its own cache tag, but also its list
585 // cache tags. (A deleted entity may cause changes in a paged list on
586 // other pages than the one it's on. The one it's on is handled by its own
587 // cache tag, but subsequent list pages would not be invalidated, hence we
588 // must invalidate its list cache tags as well.)
589 $tags = Cache::mergeTags($tags, $entity->getCacheTagsToInvalidate());
591 Cache::invalidateTags($tags);
597 public function getOriginalId() {
598 // By default, entities do not support renames and do not have original IDs.
605 public function setOriginalId($id) {
606 // By default, entities do not support renames and do not have original IDs.
607 // If the specified ID is anything except NULL, this should mark this entity
610 $this->enforceIsNew(FALSE);
619 public function toArray() {
626 public function getTypedData() {
627 if (!isset($this->typedData)) {
628 $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
629 $this->typedData = $class::createFromEntity($this);
631 return $this->typedData;
637 public function __sleep() {
638 $this->typedData = NULL;
639 return $this->traitSleep();
645 public function getConfigDependencyKey() {
646 return $this->getEntityType()->getConfigDependencyKey();
652 public function getConfigDependencyName() {
653 return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
659 public function getConfigTarget() {
660 // For content entities, use the UUID for the config target identifier.
661 // This ensures that references to the target can be deployed reliably.
662 return $this->uuid();