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 language manager.
94 * @return \Drupal\Core\Language\LanguageManagerInterface
96 protected function languageManager() {
97 return \Drupal::languageManager();
101 * Gets the UUID generator.
103 * @return \Drupal\Component\Uuid\UuidInterface
105 protected function uuidGenerator() {
106 return \Drupal::service('uuid');
112 public function id() {
113 return isset($this->id) ? $this->id : NULL;
119 public function uuid() {
120 return isset($this->uuid) ? $this->uuid : NULL;
126 public function isNew() {
127 return !empty($this->enforceIsNew) || !$this->id();
133 public function enforceIsNew($value = TRUE) {
134 $this->enforceIsNew = $value;
142 public function getEntityTypeId() {
143 return $this->entityTypeId;
149 public function bundle() {
150 return $this->entityTypeId;
156 public function label() {
158 $entity_type = $this->getEntityType();
159 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
160 $label = call_user_func($label_callback, $this);
162 elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
163 $label = $this->{$label_key};
171 public function urlInfo($rel = 'canonical', array $options = []) {
172 return $this->toUrl($rel, $options);
178 public function toUrl($rel = 'canonical', array $options = []) {
179 if ($this->id() === NULL) {
180 throw new EntityMalformedException(sprintf('The "%s" entity cannot have a URI as it does not have an ID', $this->getEntityTypeId()));
183 // The links array might contain URI templates set in annotations.
184 $link_templates = $this->linkTemplates();
186 // Links pointing to the current revision point to the actual entity. So
187 // instead of using the 'revision' link, use the 'canonical' link.
188 if ($rel === 'revision' && $this instanceof RevisionableInterface && $this->isDefaultRevision()) {
192 if (isset($link_templates[$rel])) {
193 $route_parameters = $this->urlRouteParameters($rel);
194 $route_name = "entity.{$this->entityTypeId}." . str_replace(['-', 'drupal:'], ['_', ''], $rel);
195 $uri = new Url($route_name, $route_parameters);
198 $bundle = $this->bundle();
199 // A bundle-specific callback takes precedence over the generic one for
201 $bundles = $this->entityManager()->getBundleInfo($this->getEntityTypeId());
202 if (isset($bundles[$bundle]['uri_callback'])) {
203 $uri_callback = $bundles[$bundle]['uri_callback'];
205 elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
206 $uri_callback = $entity_uri_callback;
209 // Invoke the callback to get the URI. If there is no callback, use the
210 // default URI format.
211 if (isset($uri_callback) && is_callable($uri_callback)) {
212 $uri = call_user_func($uri_callback, $this);
215 throw new UndefinedLinkTemplateException("No link template '$rel' found for the '{$this->getEntityTypeId()}' entity type");
219 // Pass the entity data through as options, so that alter functions do not
220 // need to look up this entity again.
222 ->setOption('entity_type', $this->getEntityTypeId())
223 ->setOption('entity', $this);
225 // Display links by default based on the current language.
226 // Link relations that do not require an existing entity should not be
227 // affected by this entity's language, however.
228 if (!in_array($rel, ['collection', 'add-page', 'add-form'], TRUE)) {
229 $options += ['language' => $this->language()];
232 $uri_options = $uri->getOptions();
233 $uri_options += $options;
235 return $uri->setOptions($uri_options);
241 public function hasLinkTemplate($rel) {
242 $link_templates = $this->linkTemplates();
243 return isset($link_templates[$rel]);
247 * Gets an array link templates.
250 * An array of link templates containing paths.
252 protected function linkTemplates() {
253 return $this->getEntityType()->getLinkTemplates();
259 public function link($text = NULL, $rel = 'canonical', array $options = []) {
260 return $this->toLink($text, $rel, $options)->toString();
266 public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
268 $text = $this->label();
270 $url = $this->toUrl($rel);
271 $options += $url->getOptions();
272 $url->setOptions($options);
273 return new Link($text, $url);
279 public function url($rel = 'canonical', $options = []) {
280 // While self::toUrl() will throw an exception if the entity has no id,
281 // the expected result for a URL is always a string.
282 if ($this->id() === NULL || !$this->hasLinkTemplate($rel)) {
286 $uri = $this->toUrl($rel);
287 $options += $uri->getOptions();
288 $uri->setOptions($options);
289 return $uri->toString();
293 * Gets an array of placeholders for this entity.
295 * Individual entity classes may override this method to add additional
296 * placeholders if desired. If so, they should be sure to replicate the
297 * property caching logic.
300 * The link relationship type, for example: canonical or edit-form.
303 * An array of URI placeholders.
305 protected function urlRouteParameters($rel) {
306 $uri_route_parameters = [];
308 if (!in_array($rel, ['collection', 'add-page', 'add-form'], TRUE)) {
309 // The entity ID is needed as a route parameter.
310 $uri_route_parameters[$this->getEntityTypeId()] = $this->id();
312 if ($rel === 'add-form' && ($this->getEntityType()->hasKey('bundle'))) {
313 $parameter_name = $this->getEntityType()->getBundleEntityType() ?: $this->getEntityType()->getKey('bundle');
314 $uri_route_parameters[$parameter_name] = $this->bundle();
316 if ($rel === 'revision' && $this instanceof RevisionableInterface) {
317 $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
320 return $uri_route_parameters;
326 public function uriRelationships() {
327 return array_filter(array_keys($this->linkTemplates()), function ($link_relation_type) {
328 // It's not guaranteed that every link relation type also has a
329 // corresponding route. For some, additional modules or configuration may
330 // be necessary. The interface demands that we only return supported URI
333 $this->toUrl($link_relation_type)->toString(TRUE)->getGeneratedUrl();
335 catch (RouteNotFoundException $e) {
345 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
346 if ($operation == 'create') {
347 return $this->entityManager()
348 ->getAccessControlHandler($this->entityTypeId)
349 ->createAccess($this->bundle(), $account, [], $return_as_object);
351 return $this->entityManager()
352 ->getAccessControlHandler($this->entityTypeId)
353 ->access($this, $operation, $account, $return_as_object);
359 public function language() {
360 if ($key = $this->getEntityType()->getKey('langcode')) {
361 $langcode = $this->$key;
362 $language = $this->languageManager()->getLanguage($langcode);
367 // Make sure we return a proper language object.
368 $langcode = !empty($this->langcode) ? $this->langcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
369 $language = new Language(['id' => $langcode]);
376 public function save() {
377 return $this->entityManager()->getStorage($this->entityTypeId)->save($this);
383 public function delete() {
384 if (!$this->isNew()) {
385 $this->entityManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
392 public function createDuplicate() {
393 $duplicate = clone $this;
394 $entity_type = $this->getEntityType();
395 // Reset the entity ID and indicate that this is a new entity.
396 $duplicate->{$entity_type->getKey('id')} = NULL;
397 $duplicate->enforceIsNew();
399 // Check if the entity type supports UUIDs and generate a new one if so.
400 if ($entity_type->hasKey('uuid')) {
401 $duplicate->{$entity_type->getKey('uuid')} = $this->uuidGenerator()->generate();
409 public function getEntityType() {
410 return $this->entityManager()->getDefinition($this->getEntityTypeId());
416 public function preSave(EntityStorageInterface $storage) {
417 // Check if this is an entity bundle.
418 if ($this->getEntityType()->getBundleOf()) {
419 // Throw an exception if the bundle ID is longer than 32 characters.
420 if (Unicode::strlen($this->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
421 throw new ConfigEntityIdLengthException("Attempt to create a bundle with an ID longer than " . EntityTypeInterface::BUNDLE_MAX_LENGTH . " characters: $this->id().");
429 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
430 $this->invalidateTagsOnSave($update);
436 public static function preCreate(EntityStorageInterface $storage, array &$values) {
442 public function postCreate(EntityStorageInterface $storage) {
448 public static function preDelete(EntityStorageInterface $storage, array $entities) {
454 public static function postDelete(EntityStorageInterface $storage, array $entities) {
455 static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
461 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
467 public function referencedEntities() {
474 public function getCacheContexts() {
475 return $this->cacheContexts;
481 public function getCacheTagsToInvalidate() {
482 // @todo Add bundle-specific listing cache tag?
483 // https://www.drupal.org/node/2145751
484 if ($this->isNew()) {
487 return [$this->entityTypeId . ':' . $this->id()];
493 public function getCacheTags() {
494 if ($this->cacheTags) {
495 return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
497 return $this->getCacheTagsToInvalidate();
503 public function getCacheMaxAge() {
504 return $this->cacheMaxAge;
510 public static function load($id) {
511 $entity_manager = \Drupal::entityManager();
512 return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->load($id);
518 public static function loadMultiple(array $ids = NULL) {
519 $entity_manager = \Drupal::entityManager();
520 return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->loadMultiple($ids);
526 public static function create(array $values = []) {
527 $entity_manager = \Drupal::entityManager();
528 return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->create($values);
532 * Invalidates an entity's cache tags upon save.
534 * @param bool $update
535 * TRUE if the entity has been updated, or FALSE if it has been inserted.
537 protected function invalidateTagsOnSave($update) {
538 // An entity was created or updated: invalidate its list cache tags. (An
539 // updated entity may start to appear in a listing because it now meets that
540 // listing's filtering requirements. A newly created entity may start to
541 // appear in listings because it did not exist before.)
542 $tags = $this->getEntityType()->getListCacheTags();
543 if ($this->hasLinkTemplate('canonical')) {
544 // Creating or updating an entity may change a cached 403 or 404 response.
545 $tags = Cache::mergeTags($tags, ['4xx-response']);
548 // An existing entity was updated, also invalidate its unique cache tag.
549 $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
551 Cache::invalidateTags($tags);
555 * Invalidates an entity's cache tags upon delete.
557 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
558 * The entity type definition.
559 * @param \Drupal\Core\Entity\EntityInterface[] $entities
560 * An array of entities.
562 protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
563 $tags = $entity_type->getListCacheTags();
564 foreach ($entities as $entity) {
565 // An entity was deleted: invalidate its own cache tag, but also its list
566 // cache tags. (A deleted entity may cause changes in a paged list on
567 // other pages than the one it's on. The one it's on is handled by its own
568 // cache tag, but subsequent list pages would not be invalidated, hence we
569 // must invalidate its list cache tags as well.)
570 $tags = Cache::mergeTags($tags, $entity->getCacheTagsToInvalidate());
572 Cache::invalidateTags($tags);
578 public function getOriginalId() {
579 // By default, entities do not support renames and do not have original IDs.
586 public function setOriginalId($id) {
587 // By default, entities do not support renames and do not have original IDs.
588 // If the specified ID is anything except NULL, this should mark this entity
591 $this->enforceIsNew(FALSE);
600 public function toArray() {
607 public function getTypedData() {
608 if (!isset($this->typedData)) {
609 $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
610 $this->typedData = $class::createFromEntity($this);
612 return $this->typedData;
618 public function __sleep() {
619 $this->typedData = NULL;
620 return $this->traitSleep();
626 public function getConfigDependencyKey() {
627 return $this->getEntityType()->getConfigDependencyKey();
633 public function getConfigDependencyName() {
634 return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
640 public function getConfigTarget() {
641 // For content entities, use the UUID for the config target identifier.
642 // This ensures that references to the target can be deployed reliably.
643 return $this->uuid();