4fe37866f13570c88807c7860a7f030e719ecbe9
[yaffs-website] / web / core / lib / Drupal / Core / Entity / Entity.php
1 <?php
2
3 namespace Drupal\Core\Entity;
4
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;
13 use Drupal\Core\Link;
14 use Drupal\Core\Session\AccountInterface;
15 use Drupal\Core\Url;
16 use Symfony\Component\Routing\Exception\RouteNotFoundException;
17
18 /**
19  * Defines a base entity class.
20  */
21 abstract class Entity implements EntityInterface {
22
23   use RefinableCacheableDependencyTrait;
24
25   use DependencySerializationTrait {
26     __sleep as traitSleep;
27   }
28
29   /**
30    * The entity type.
31    *
32    * @var string
33    */
34   protected $entityTypeId;
35
36   /**
37    * Boolean indicating whether the entity should be forced to be new.
38    *
39    * @var bool
40    */
41   protected $enforceIsNew;
42
43   /**
44    * A typed data object wrapping this entity.
45    *
46    * @var \Drupal\Core\TypedData\ComplexDataInterface
47    */
48   protected $typedData;
49
50   /**
51    * Constructs an Entity object.
52    *
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.
58    */
59   public function __construct(array $values, $entity_type) {
60     $this->entityTypeId = $entity_type;
61     // Set initial values.
62     foreach ($values as $key => $value) {
63       $this->$key = $value;
64     }
65   }
66
67   /**
68    * Gets the entity manager.
69    *
70    * @return \Drupal\Core\Entity\EntityManagerInterface
71    *
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.
77    */
78   protected function entityManager() {
79     return \Drupal::entityManager();
80   }
81
82   /**
83    * Gets the entity type manager.
84    *
85    * @return \Drupal\Core\Entity\EntityTypeManagerInterface
86    */
87   protected function entityTypeManager() {
88     return \Drupal::entityTypeManager();
89   }
90
91   /**
92    * Gets the entity type bundle info service.
93    *
94    * @return \Drupal\Core\Entity\EntityTypeBundleInfoInterface
95    */
96   protected function entityTypeBundleInfo() {
97     return \Drupal::service('entity_type.bundle.info');
98   }
99
100   /**
101    * Gets the language manager.
102    *
103    * @return \Drupal\Core\Language\LanguageManagerInterface
104    */
105   protected function languageManager() {
106     return \Drupal::languageManager();
107   }
108
109   /**
110    * Gets the UUID generator.
111    *
112    * @return \Drupal\Component\Uuid\UuidInterface
113    */
114   protected function uuidGenerator() {
115     return \Drupal::service('uuid');
116   }
117
118   /**
119    * {@inheritdoc}
120    */
121   public function id() {
122     return isset($this->id) ? $this->id : NULL;
123   }
124
125   /**
126    * {@inheritdoc}
127    */
128   public function uuid() {
129     return isset($this->uuid) ? $this->uuid : NULL;
130   }
131
132   /**
133    * {@inheritdoc}
134    */
135   public function isNew() {
136     return !empty($this->enforceIsNew) || !$this->id();
137   }
138
139   /**
140    * {@inheritdoc}
141    */
142   public function enforceIsNew($value = TRUE) {
143     $this->enforceIsNew = $value;
144
145     return $this;
146   }
147
148   /**
149    * {@inheritdoc}
150    */
151   public function getEntityTypeId() {
152     return $this->entityTypeId;
153   }
154
155   /**
156    * {@inheritdoc}
157    */
158   public function bundle() {
159     return $this->entityTypeId;
160   }
161
162   /**
163    * {@inheritdoc}
164    */
165   public function label() {
166     $label = NULL;
167     $entity_type = $this->getEntityType();
168     if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
169       $label = call_user_func($label_callback, $this);
170     }
171     elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
172       $label = $this->{$label_key};
173     }
174     return $label;
175   }
176
177   /**
178    * {@inheritdoc}
179    */
180   public function urlInfo($rel = 'canonical', array $options = []) {
181     return $this->toUrl($rel, $options);
182   }
183
184   /**
185    * {@inheritdoc}
186    */
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()));
190     }
191
192     // The links array might contain URI templates set in annotations.
193     $link_templates = $this->linkTemplates();
194
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()) {
198       $rel = 'canonical';
199     }
200
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);
205     }
206     else {
207       $bundle = $this->bundle();
208       // A bundle-specific callback takes precedence over the generic one for
209       // the entity type.
210       $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->getEntityTypeId());
211       if (isset($bundles[$bundle]['uri_callback'])) {
212         $uri_callback = $bundles[$bundle]['uri_callback'];
213       }
214       elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
215         $uri_callback = $entity_uri_callback;
216       }
217
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);
222       }
223       else {
224         throw new UndefinedLinkTemplateException("No link template '$rel' found for the '{$this->getEntityTypeId()}' entity type");
225       }
226     }
227
228     // Pass the entity data through as options, so that alter functions do not
229     // need to look up this entity again.
230     $uri
231       ->setOption('entity_type', $this->getEntityTypeId())
232       ->setOption('entity', $this);
233
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()];
239     }
240
241     $uri_options = $uri->getOptions();
242     $uri_options += $options;
243
244     return $uri->setOptions($uri_options);
245   }
246
247   /**
248    * {@inheritdoc}
249    */
250   public function hasLinkTemplate($rel) {
251     $link_templates = $this->linkTemplates();
252     return isset($link_templates[$rel]);
253   }
254
255   /**
256    * Gets an array link templates.
257    *
258    * @return array
259    *   An array of link templates containing paths.
260    */
261   protected function linkTemplates() {
262     return $this->getEntityType()->getLinkTemplates();
263   }
264
265   /**
266    * {@inheritdoc}
267    */
268   public function link($text = NULL, $rel = 'canonical', array $options = []) {
269     return $this->toLink($text, $rel, $options)->toString();
270   }
271
272   /**
273    * {@inheritdoc}
274    */
275   public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
276     if (!isset($text)) {
277       $text = $this->label();
278     }
279     $url = $this->toUrl($rel);
280     $options += $url->getOptions();
281     $url->setOptions($options);
282     return new Link($text, $url);
283   }
284
285   /**
286    * {@inheritdoc}
287    */
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)) {
292       return '';
293     }
294
295     $uri = $this->toUrl($rel);
296     $options += $uri->getOptions();
297     $uri->setOptions($options);
298     return $uri->toString();
299   }
300
301   /**
302    * Gets an array of placeholders for this entity.
303    *
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.
307    *
308    * @param string $rel
309    *   The link relationship type, for example: canonical or edit-form.
310    *
311    * @return array
312    *   An array of URI placeholders.
313    */
314   protected function urlRouteParameters($rel) {
315     $uri_route_parameters = [];
316
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();
320     }
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();
324     }
325     if ($rel === 'revision' && $this instanceof RevisionableInterface) {
326       $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
327     }
328
329     return $uri_route_parameters;
330   }
331
332   /**
333    * {@inheritdoc}
334    */
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
340       // relationships.
341       try {
342         $this->toUrl($link_relation_type)->toString(TRUE)->getGeneratedUrl();
343       }
344       catch (RouteNotFoundException $e) {
345         return FALSE;
346       }
347       return TRUE;
348     });
349   }
350
351   /**
352    * {@inheritdoc}
353    */
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);
359     }
360     return $this->entityTypeManager()
361       ->getAccessControlHandler($this->entityTypeId)
362       ->access($this, $operation, $account, $return_as_object);
363   }
364
365   /**
366    * {@inheritdoc}
367    */
368   public function language() {
369     if ($key = $this->getEntityType()->getKey('langcode')) {
370       $langcode = $this->$key;
371       $language = $this->languageManager()->getLanguage($langcode);
372       if ($language) {
373         return $language;
374       }
375     }
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]);
379     return $language;
380   }
381
382   /**
383    * {@inheritdoc}
384    */
385   public function save() {
386     $storage = $this->entityTypeManager()->getStorage($this->entityTypeId);
387     return $storage->save($this);
388   }
389
390   /**
391    * {@inheritdoc}
392    */
393   public function delete() {
394     if (!$this->isNew()) {
395       $this->entityTypeManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
396     }
397   }
398
399   /**
400    * {@inheritdoc}
401    */
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();
408
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();
412     }
413     return $duplicate;
414   }
415
416   /**
417    * {@inheritdoc}
418    */
419   public function getEntityType() {
420     return $this->entityTypeManager()->getDefinition($this->getEntityTypeId());
421   }
422
423   /**
424    * {@inheritdoc}
425    */
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().");
432       }
433     }
434   }
435
436   /**
437    * {@inheritdoc}
438    */
439   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
440     $this->invalidateTagsOnSave($update);
441   }
442
443   /**
444    * {@inheritdoc}
445    */
446   public static function preCreate(EntityStorageInterface $storage, array &$values) {
447   }
448
449   /**
450    * {@inheritdoc}
451    */
452   public function postCreate(EntityStorageInterface $storage) {
453   }
454
455   /**
456    * {@inheritdoc}
457    */
458   public static function preDelete(EntityStorageInterface $storage, array $entities) {
459   }
460
461   /**
462    * {@inheritdoc}
463    */
464   public static function postDelete(EntityStorageInterface $storage, array $entities) {
465     static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
466   }
467
468   /**
469    * {@inheritdoc}
470    */
471   public static function postLoad(EntityStorageInterface $storage, array &$entities) {
472   }
473
474   /**
475    * {@inheritdoc}
476    */
477   public function referencedEntities() {
478     return [];
479   }
480
481   /**
482    * {@inheritdoc}
483    */
484   public function getCacheContexts() {
485     return $this->cacheContexts;
486   }
487
488   /**
489    * {@inheritdoc}
490    */
491   public function getCacheTagsToInvalidate() {
492     // @todo Add bundle-specific listing cache tag?
493     //   https://www.drupal.org/node/2145751
494     if ($this->isNew()) {
495       return [];
496     }
497     return [$this->entityTypeId . ':' . $this->id()];
498   }
499
500   /**
501    * {@inheritdoc}
502    */
503   public function getCacheTags() {
504     if ($this->cacheTags) {
505       return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
506     }
507     return $this->getCacheTagsToInvalidate();
508   }
509
510   /**
511    * {@inheritdoc}
512    */
513   public function getCacheMaxAge() {
514     return $this->cacheMaxAge;
515   }
516
517   /**
518    * {@inheritdoc}
519    */
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);
525   }
526
527   /**
528    * {@inheritdoc}
529    */
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);
535   }
536
537   /**
538    * {@inheritdoc}
539    */
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);
545   }
546
547   /**
548    * Invalidates an entity's cache tags upon save.
549    *
550    * @param bool $update
551    *   TRUE if the entity has been updated, or FALSE if it has been inserted.
552    */
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']);
562     }
563     if ($update) {
564       // An existing entity was updated, also invalidate its unique cache tag.
565       $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
566     }
567     Cache::invalidateTags($tags);
568   }
569
570   /**
571    * Invalidates an entity's cache tags upon delete.
572    *
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.
577    */
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());
587     }
588     Cache::invalidateTags($tags);
589   }
590
591   /**
592    * {@inheritdoc}
593    */
594   public function getOriginalId() {
595     // By default, entities do not support renames and do not have original IDs.
596     return NULL;
597   }
598
599   /**
600    * {@inheritdoc}
601    */
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
605     // as no longer new.
606     if ($id !== NULL) {
607       $this->enforceIsNew(FALSE);
608     }
609
610     return $this;
611   }
612
613   /**
614    * {@inheritdoc}
615    */
616   public function toArray() {
617     return [];
618   }
619
620   /**
621    * {@inheritdoc}
622    */
623   public function getTypedData() {
624     if (!isset($this->typedData)) {
625       $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
626       $this->typedData = $class::createFromEntity($this);
627     }
628     return $this->typedData;
629   }
630
631   /**
632    * {@inheritdoc}
633    */
634   public function __sleep() {
635     $this->typedData = NULL;
636     return $this->traitSleep();
637   }
638
639   /**
640    * {@inheritdoc}
641    */
642   public function getConfigDependencyKey() {
643     return $this->getEntityType()->getConfigDependencyKey();
644   }
645
646   /**
647    * {@inheritdoc}
648    */
649   public function getConfigDependencyName() {
650     return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
651   }
652
653   /**
654    * {@inheritdoc}
655    */
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();
660   }
661
662 }