84991bc60935ccd993c313b3ac512d6b90344a3e
[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\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
9 use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
10 use Drupal\Core\Language\Language;
11 use Drupal\Core\Language\LanguageInterface;
12 use Drupal\Core\Link;
13 use Drupal\Core\Session\AccountInterface;
14 use Drupal\Core\Url;
15 use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
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       catch (MissingMandatoryParametersException $e) {
348         return FALSE;
349       }
350       return TRUE;
351     });
352   }
353
354   /**
355    * {@inheritdoc}
356    */
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);
362     }
363     return $this->entityTypeManager()
364       ->getAccessControlHandler($this->entityTypeId)
365       ->access($this, $operation, $account, $return_as_object);
366   }
367
368   /**
369    * {@inheritdoc}
370    */
371   public function language() {
372     if ($key = $this->getEntityType()->getKey('langcode')) {
373       $langcode = $this->$key;
374       $language = $this->languageManager()->getLanguage($langcode);
375       if ($language) {
376         return $language;
377       }
378     }
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]);
382     return $language;
383   }
384
385   /**
386    * {@inheritdoc}
387    */
388   public function save() {
389     $storage = $this->entityTypeManager()->getStorage($this->entityTypeId);
390     return $storage->save($this);
391   }
392
393   /**
394    * {@inheritdoc}
395    */
396   public function delete() {
397     if (!$this->isNew()) {
398       $this->entityTypeManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
399     }
400   }
401
402   /**
403    * {@inheritdoc}
404    */
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();
411
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();
415     }
416     return $duplicate;
417   }
418
419   /**
420    * {@inheritdoc}
421    */
422   public function getEntityType() {
423     return $this->entityTypeManager()->getDefinition($this->getEntityTypeId());
424   }
425
426   /**
427    * {@inheritdoc}
428    */
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().");
435       }
436     }
437   }
438
439   /**
440    * {@inheritdoc}
441    */
442   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
443     $this->invalidateTagsOnSave($update);
444   }
445
446   /**
447    * {@inheritdoc}
448    */
449   public static function preCreate(EntityStorageInterface $storage, array &$values) {
450   }
451
452   /**
453    * {@inheritdoc}
454    */
455   public function postCreate(EntityStorageInterface $storage) {
456   }
457
458   /**
459    * {@inheritdoc}
460    */
461   public static function preDelete(EntityStorageInterface $storage, array $entities) {
462   }
463
464   /**
465    * {@inheritdoc}
466    */
467   public static function postDelete(EntityStorageInterface $storage, array $entities) {
468     static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
469   }
470
471   /**
472    * {@inheritdoc}
473    */
474   public static function postLoad(EntityStorageInterface $storage, array &$entities) {
475   }
476
477   /**
478    * {@inheritdoc}
479    */
480   public function referencedEntities() {
481     return [];
482   }
483
484   /**
485    * {@inheritdoc}
486    */
487   public function getCacheContexts() {
488     return $this->cacheContexts;
489   }
490
491   /**
492    * {@inheritdoc}
493    */
494   public function getCacheTagsToInvalidate() {
495     // @todo Add bundle-specific listing cache tag?
496     //   https://www.drupal.org/node/2145751
497     if ($this->isNew()) {
498       return [];
499     }
500     return [$this->entityTypeId . ':' . $this->id()];
501   }
502
503   /**
504    * {@inheritdoc}
505    */
506   public function getCacheTags() {
507     if ($this->cacheTags) {
508       return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
509     }
510     return $this->getCacheTagsToInvalidate();
511   }
512
513   /**
514    * {@inheritdoc}
515    */
516   public function getCacheMaxAge() {
517     return $this->cacheMaxAge;
518   }
519
520   /**
521    * {@inheritdoc}
522    */
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);
528   }
529
530   /**
531    * {@inheritdoc}
532    */
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);
538   }
539
540   /**
541    * {@inheritdoc}
542    */
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);
548   }
549
550   /**
551    * Invalidates an entity's cache tags upon save.
552    *
553    * @param bool $update
554    *   TRUE if the entity has been updated, or FALSE if it has been inserted.
555    */
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']);
565     }
566     if ($update) {
567       // An existing entity was updated, also invalidate its unique cache tag.
568       $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
569     }
570     Cache::invalidateTags($tags);
571   }
572
573   /**
574    * Invalidates an entity's cache tags upon delete.
575    *
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.
580    */
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());
590     }
591     Cache::invalidateTags($tags);
592   }
593
594   /**
595    * {@inheritdoc}
596    */
597   public function getOriginalId() {
598     // By default, entities do not support renames and do not have original IDs.
599     return NULL;
600   }
601
602   /**
603    * {@inheritdoc}
604    */
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
608     // as no longer new.
609     if ($id !== NULL) {
610       $this->enforceIsNew(FALSE);
611     }
612
613     return $this;
614   }
615
616   /**
617    * {@inheritdoc}
618    */
619   public function toArray() {
620     return [];
621   }
622
623   /**
624    * {@inheritdoc}
625    */
626   public function getTypedData() {
627     if (!isset($this->typedData)) {
628       $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
629       $this->typedData = $class::createFromEntity($this);
630     }
631     return $this->typedData;
632   }
633
634   /**
635    * {@inheritdoc}
636    */
637   public function __sleep() {
638     $this->typedData = NULL;
639     return $this->traitSleep();
640   }
641
642   /**
643    * {@inheritdoc}
644    */
645   public function getConfigDependencyKey() {
646     return $this->getEntityType()->getConfigDependencyKey();
647   }
648
649   /**
650    * {@inheritdoc}
651    */
652   public function getConfigDependencyName() {
653     return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
654   }
655
656   /**
657    * {@inheritdoc}
658    */
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();
663   }
664
665 }