comparison core/lib/Drupal/Core/Entity/EntityBase.php @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents
children
comparison
equal deleted inserted replaced
4:a9cd425dd02b 5:12f9dff5fda9
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 EntityBase 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 @trigger_error('Entity::getEntityManager() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use ::getEntityTypeManager() instead. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
80 return \Drupal::entityManager();
81 }
82
83 /**
84 * Gets the entity type manager.
85 *
86 * @return \Drupal\Core\Entity\EntityTypeManagerInterface
87 */
88 protected function entityTypeManager() {
89 return \Drupal::entityTypeManager();
90 }
91
92 /**
93 * Gets the entity type bundle info service.
94 *
95 * @return \Drupal\Core\Entity\EntityTypeBundleInfoInterface
96 */
97 protected function entityTypeBundleInfo() {
98 return \Drupal::service('entity_type.bundle.info');
99 }
100
101 /**
102 * Gets the language manager.
103 *
104 * @return \Drupal\Core\Language\LanguageManagerInterface
105 */
106 protected function languageManager() {
107 return \Drupal::languageManager();
108 }
109
110 /**
111 * Gets the UUID generator.
112 *
113 * @return \Drupal\Component\Uuid\UuidInterface
114 */
115 protected function uuidGenerator() {
116 return \Drupal::service('uuid');
117 }
118
119 /**
120 * {@inheritdoc}
121 */
122 public function id() {
123 return isset($this->id) ? $this->id : NULL;
124 }
125
126 /**
127 * {@inheritdoc}
128 */
129 public function uuid() {
130 return isset($this->uuid) ? $this->uuid : NULL;
131 }
132
133 /**
134 * {@inheritdoc}
135 */
136 public function isNew() {
137 return !empty($this->enforceIsNew) || !$this->id();
138 }
139
140 /**
141 * {@inheritdoc}
142 */
143 public function enforceIsNew($value = TRUE) {
144 $this->enforceIsNew = $value;
145
146 return $this;
147 }
148
149 /**
150 * {@inheritdoc}
151 */
152 public function getEntityTypeId() {
153 return $this->entityTypeId;
154 }
155
156 /**
157 * {@inheritdoc}
158 */
159 public function bundle() {
160 return $this->entityTypeId;
161 }
162
163 /**
164 * {@inheritdoc}
165 */
166 public function label() {
167 $label = NULL;
168 $entity_type = $this->getEntityType();
169 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
170 $label = call_user_func($label_callback, $this);
171 }
172 elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
173 $label = $this->{$label_key};
174 }
175 return $label;
176 }
177
178 /**
179 * {@inheritdoc}
180 */
181 public function urlInfo($rel = 'canonical', array $options = []) {
182 @trigger_error('EntityInterface::urlInfo() is deprecated in Drupal 8.0.0 and will be removed in Drupal 9.0.0. EntityInterface::toUrl() instead. See https://www.drupal.org/node/2614344', E_USER_DEPRECATED);
183 return $this->toUrl($rel, $options);
184 }
185
186 /**
187 * {@inheritdoc}
188 */
189 public function toUrl($rel = 'canonical', array $options = []) {
190 if ($this->id() === NULL) {
191 throw new EntityMalformedException(sprintf('The "%s" entity cannot have a URI as it does not have an ID', $this->getEntityTypeId()));
192 }
193
194 // The links array might contain URI templates set in annotations.
195 $link_templates = $this->linkTemplates();
196
197 // Links pointing to the current revision point to the actual entity. So
198 // instead of using the 'revision' link, use the 'canonical' link.
199 if ($rel === 'revision' && $this instanceof RevisionableInterface && $this->isDefaultRevision()) {
200 $rel = 'canonical';
201 }
202
203 if (isset($link_templates[$rel])) {
204 $route_parameters = $this->urlRouteParameters($rel);
205 $route_name = "entity.{$this->entityTypeId}." . str_replace(['-', 'drupal:'], ['_', ''], $rel);
206 $uri = new Url($route_name, $route_parameters);
207 }
208 else {
209 $bundle = $this->bundle();
210 // A bundle-specific callback takes precedence over the generic one for
211 // the entity type.
212 $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->getEntityTypeId());
213 if (isset($bundles[$bundle]['uri_callback'])) {
214 $uri_callback = $bundles[$bundle]['uri_callback'];
215 }
216 elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
217 $uri_callback = $entity_uri_callback;
218 }
219
220 // Invoke the callback to get the URI. If there is no callback, use the
221 // default URI format.
222 if (isset($uri_callback) && is_callable($uri_callback)) {
223 $uri = call_user_func($uri_callback, $this);
224 }
225 else {
226 throw new UndefinedLinkTemplateException("No link template '$rel' found for the '{$this->getEntityTypeId()}' entity type");
227 }
228 }
229
230 // Pass the entity data through as options, so that alter functions do not
231 // need to look up this entity again.
232 $uri
233 ->setOption('entity_type', $this->getEntityTypeId())
234 ->setOption('entity', $this);
235
236 // Display links by default based on the current language.
237 // Link relations that do not require an existing entity should not be
238 // affected by this entity's language, however.
239 if (!in_array($rel, ['collection', 'add-page', 'add-form'], TRUE)) {
240 $options += ['language' => $this->language()];
241 }
242
243 $uri_options = $uri->getOptions();
244 $uri_options += $options;
245
246 return $uri->setOptions($uri_options);
247 }
248
249 /**
250 * {@inheritdoc}
251 */
252 public function hasLinkTemplate($rel) {
253 $link_templates = $this->linkTemplates();
254 return isset($link_templates[$rel]);
255 }
256
257 /**
258 * Gets an array link templates.
259 *
260 * @return array
261 * An array of link templates containing paths.
262 */
263 protected function linkTemplates() {
264 return $this->getEntityType()->getLinkTemplates();
265 }
266
267 /**
268 * {@inheritdoc}
269 */
270 public function link($text = NULL, $rel = 'canonical', array $options = []) {
271 @trigger_error("EntityInterface::link() is deprecated in Drupal 8.0.0 and will be removed in Drupal 9.0.0. EntityInterface::toLink() instead. Note, the default relationship for configuration entities changes from 'edit-form' to 'canonical'. See https://www.drupal.org/node/2614344", E_USER_DEPRECATED);
272 return $this->toLink($text, $rel, $options)->toString();
273 }
274
275 /**
276 * {@inheritdoc}
277 */
278 public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
279 if (!isset($text)) {
280 $text = $this->label();
281 }
282 $url = $this->toUrl($rel);
283 $options += $url->getOptions();
284 $url->setOptions($options);
285 return new Link($text, $url);
286 }
287
288 /**
289 * {@inheritdoc}
290 */
291 public function url($rel = 'canonical', $options = []) {
292 @trigger_error('EntityInterface::url() is deprecated in Drupal 8.0.0 and will be removed in Drupal 9.0.0. EntityInterface::toUrl() instead. Note, a \Drupal\Core\Url object is returned. See https://www.drupal.org/node/2614344', E_USER_DEPRECATED);
293 // While self::toUrl() will throw an exception if the entity has no id,
294 // the expected result for a URL is always a string.
295 if ($this->id() === NULL || !$this->hasLinkTemplate($rel)) {
296 return '';
297 }
298
299 $uri = $this->toUrl($rel);
300 $options += $uri->getOptions();
301 $uri->setOptions($options);
302 return $uri->toString();
303 }
304
305 /**
306 * Gets an array of placeholders for this entity.
307 *
308 * Individual entity classes may override this method to add additional
309 * placeholders if desired. If so, they should be sure to replicate the
310 * property caching logic.
311 *
312 * @param string $rel
313 * The link relationship type, for example: canonical or edit-form.
314 *
315 * @return array
316 * An array of URI placeholders.
317 */
318 protected function urlRouteParameters($rel) {
319 $uri_route_parameters = [];
320
321 if (!in_array($rel, ['collection', 'add-page', 'add-form'], TRUE)) {
322 // The entity ID is needed as a route parameter.
323 $uri_route_parameters[$this->getEntityTypeId()] = $this->id();
324 }
325 if ($rel === 'add-form' && ($this->getEntityType()->hasKey('bundle'))) {
326 $parameter_name = $this->getEntityType()->getBundleEntityType() ?: $this->getEntityType()->getKey('bundle');
327 $uri_route_parameters[$parameter_name] = $this->bundle();
328 }
329 if ($rel === 'revision' && $this instanceof RevisionableInterface) {
330 $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
331 }
332
333 return $uri_route_parameters;
334 }
335
336 /**
337 * {@inheritdoc}
338 */
339 public function uriRelationships() {
340 return array_filter(array_keys($this->linkTemplates()), function ($link_relation_type) {
341 // It's not guaranteed that every link relation type also has a
342 // corresponding route. For some, additional modules or configuration may
343 // be necessary. The interface demands that we only return supported URI
344 // relationships.
345 try {
346 $this->toUrl($link_relation_type)->toString(TRUE)->getGeneratedUrl();
347 }
348 catch (RouteNotFoundException $e) {
349 return FALSE;
350 }
351 catch (MissingMandatoryParametersException $e) {
352 return FALSE;
353 }
354 return TRUE;
355 });
356 }
357
358 /**
359 * {@inheritdoc}
360 */
361 public function access($operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
362 if ($operation == 'create') {
363 return $this->entityTypeManager()
364 ->getAccessControlHandler($this->entityTypeId)
365 ->createAccess($this->bundle(), $account, [], $return_as_object);
366 }
367 return $this->entityTypeManager()
368 ->getAccessControlHandler($this->entityTypeId)
369 ->access($this, $operation, $account, $return_as_object);
370 }
371
372 /**
373 * {@inheritdoc}
374 */
375 public function language() {
376 if ($key = $this->getEntityType()->getKey('langcode')) {
377 $langcode = $this->$key;
378 $language = $this->languageManager()->getLanguage($langcode);
379 if ($language) {
380 return $language;
381 }
382 }
383 // Make sure we return a proper language object.
384 $langcode = !empty($this->langcode) ? $this->langcode : LanguageInterface::LANGCODE_NOT_SPECIFIED;
385 $language = new Language(['id' => $langcode]);
386 return $language;
387 }
388
389 /**
390 * {@inheritdoc}
391 */
392 public function save() {
393 $storage = $this->entityTypeManager()->getStorage($this->entityTypeId);
394 return $storage->save($this);
395 }
396
397 /**
398 * {@inheritdoc}
399 */
400 public function delete() {
401 if (!$this->isNew()) {
402 $this->entityTypeManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
403 }
404 }
405
406 /**
407 * {@inheritdoc}
408 */
409 public function createDuplicate() {
410 $duplicate = clone $this;
411 $entity_type = $this->getEntityType();
412 // Reset the entity ID and indicate that this is a new entity.
413 $duplicate->{$entity_type->getKey('id')} = NULL;
414 $duplicate->enforceIsNew();
415
416 // Check if the entity type supports UUIDs and generate a new one if so.
417 if ($entity_type->hasKey('uuid')) {
418 $duplicate->{$entity_type->getKey('uuid')} = $this->uuidGenerator()->generate();
419 }
420 return $duplicate;
421 }
422
423 /**
424 * {@inheritdoc}
425 */
426 public function getEntityType() {
427 return $this->entityTypeManager()->getDefinition($this->getEntityTypeId());
428 }
429
430 /**
431 * {@inheritdoc}
432 */
433 public function preSave(EntityStorageInterface $storage) {
434 // Check if this is an entity bundle.
435 if ($this->getEntityType()->getBundleOf()) {
436 // Throw an exception if the bundle ID is longer than 32 characters.
437 if (mb_strlen($this->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
438 throw new ConfigEntityIdLengthException("Attempt to create a bundle with an ID longer than " . EntityTypeInterface::BUNDLE_MAX_LENGTH . " characters: $this->id().");
439 }
440 }
441 }
442
443 /**
444 * {@inheritdoc}
445 */
446 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
447 $this->invalidateTagsOnSave($update);
448 }
449
450 /**
451 * {@inheritdoc}
452 */
453 public static function preCreate(EntityStorageInterface $storage, array &$values) {
454 }
455
456 /**
457 * {@inheritdoc}
458 */
459 public function postCreate(EntityStorageInterface $storage) {
460 }
461
462 /**
463 * {@inheritdoc}
464 */
465 public static function preDelete(EntityStorageInterface $storage, array $entities) {
466 }
467
468 /**
469 * {@inheritdoc}
470 */
471 public static function postDelete(EntityStorageInterface $storage, array $entities) {
472 static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
473 }
474
475 /**
476 * {@inheritdoc}
477 */
478 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
479 }
480
481 /**
482 * {@inheritdoc}
483 */
484 public function referencedEntities() {
485 return [];
486 }
487
488 /**
489 * {@inheritdoc}
490 */
491 public function getCacheContexts() {
492 return $this->cacheContexts;
493 }
494
495 /**
496 * {@inheritdoc}
497 */
498 public function getCacheTagsToInvalidate() {
499 // @todo Add bundle-specific listing cache tag?
500 // https://www.drupal.org/node/2145751
501 if ($this->isNew()) {
502 return [];
503 }
504 return [$this->entityTypeId . ':' . $this->id()];
505 }
506
507 /**
508 * {@inheritdoc}
509 */
510 public function getCacheTags() {
511 if ($this->cacheTags) {
512 return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
513 }
514 return $this->getCacheTagsToInvalidate();
515 }
516
517 /**
518 * {@inheritdoc}
519 */
520 public function getCacheMaxAge() {
521 return $this->cacheMaxAge;
522 }
523
524 /**
525 * {@inheritdoc}
526 */
527 public static function load($id) {
528 $entity_type_repository = \Drupal::service('entity_type.repository');
529 $entity_type_manager = \Drupal::entityTypeManager();
530 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
531 return $storage->load($id);
532 }
533
534 /**
535 * {@inheritdoc}
536 */
537 public static function loadMultiple(array $ids = NULL) {
538 $entity_type_repository = \Drupal::service('entity_type.repository');
539 $entity_type_manager = \Drupal::entityTypeManager();
540 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
541 return $storage->loadMultiple($ids);
542 }
543
544 /**
545 * {@inheritdoc}
546 */
547 public static function create(array $values = []) {
548 $entity_type_repository = \Drupal::service('entity_type.repository');
549 $entity_type_manager = \Drupal::entityTypeManager();
550 $storage = $entity_type_manager->getStorage($entity_type_repository->getEntityTypeFromClass(get_called_class()));
551 return $storage->create($values);
552 }
553
554 /**
555 * Invalidates an entity's cache tags upon save.
556 *
557 * @param bool $update
558 * TRUE if the entity has been updated, or FALSE if it has been inserted.
559 */
560 protected function invalidateTagsOnSave($update) {
561 // An entity was created or updated: invalidate its list cache tags. (An
562 // updated entity may start to appear in a listing because it now meets that
563 // listing's filtering requirements. A newly created entity may start to
564 // appear in listings because it did not exist before.)
565 $tags = $this->getEntityType()->getListCacheTags();
566 if ($this->hasLinkTemplate('canonical')) {
567 // Creating or updating an entity may change a cached 403 or 404 response.
568 $tags = Cache::mergeTags($tags, ['4xx-response']);
569 }
570 if ($update) {
571 // An existing entity was updated, also invalidate its unique cache tag.
572 $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
573 }
574 Cache::invalidateTags($tags);
575 }
576
577 /**
578 * Invalidates an entity's cache tags upon delete.
579 *
580 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
581 * The entity type definition.
582 * @param \Drupal\Core\Entity\EntityInterface[] $entities
583 * An array of entities.
584 */
585 protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
586 $tags = $entity_type->getListCacheTags();
587 foreach ($entities as $entity) {
588 // An entity was deleted: invalidate its own cache tag, but also its list
589 // cache tags. (A deleted entity may cause changes in a paged list on
590 // other pages than the one it's on. The one it's on is handled by its own
591 // cache tag, but subsequent list pages would not be invalidated, hence we
592 // must invalidate its list cache tags as well.)
593 $tags = Cache::mergeTags($tags, $entity->getCacheTagsToInvalidate());
594 }
595 Cache::invalidateTags($tags);
596 }
597
598 /**
599 * {@inheritdoc}
600 */
601 public function getOriginalId() {
602 // By default, entities do not support renames and do not have original IDs.
603 return NULL;
604 }
605
606 /**
607 * {@inheritdoc}
608 */
609 public function setOriginalId($id) {
610 // By default, entities do not support renames and do not have original IDs.
611 // If the specified ID is anything except NULL, this should mark this entity
612 // as no longer new.
613 if ($id !== NULL) {
614 $this->enforceIsNew(FALSE);
615 }
616
617 return $this;
618 }
619
620 /**
621 * {@inheritdoc}
622 */
623 public function toArray() {
624 return [];
625 }
626
627 /**
628 * {@inheritdoc}
629 */
630 public function getTypedData() {
631 if (!isset($this->typedData)) {
632 $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
633 $this->typedData = $class::createFromEntity($this);
634 }
635 return $this->typedData;
636 }
637
638 /**
639 * {@inheritdoc}
640 */
641 public function __sleep() {
642 $this->typedData = NULL;
643 return $this->traitSleep();
644 }
645
646 /**
647 * {@inheritdoc}
648 */
649 public function getConfigDependencyKey() {
650 return $this->getEntityType()->getConfigDependencyKey();
651 }
652
653 /**
654 * {@inheritdoc}
655 */
656 public function getConfigDependencyName() {
657 return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
658 }
659
660 /**
661 * {@inheritdoc}
662 */
663 public function getConfigTarget() {
664 // For content entities, use the UUID for the config target identifier.
665 // This ensures that references to the target can be deployed reliably.
666 return $this->uuid();
667 }
668
669 }