comparison core/lib/Drupal/Core/Entity/Entity.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
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 language manager.
93 *
94 * @return \Drupal\Core\Language\LanguageManagerInterface
95 */
96 protected function languageManager() {
97 return \Drupal::languageManager();
98 }
99
100 /**
101 * Gets the UUID generator.
102 *
103 * @return \Drupal\Component\Uuid\UuidInterface
104 */
105 protected function uuidGenerator() {
106 return \Drupal::service('uuid');
107 }
108
109 /**
110 * {@inheritdoc}
111 */
112 public function id() {
113 return isset($this->id) ? $this->id : NULL;
114 }
115
116 /**
117 * {@inheritdoc}
118 */
119 public function uuid() {
120 return isset($this->uuid) ? $this->uuid : NULL;
121 }
122
123 /**
124 * {@inheritdoc}
125 */
126 public function isNew() {
127 return !empty($this->enforceIsNew) || !$this->id();
128 }
129
130 /**
131 * {@inheritdoc}
132 */
133 public function enforceIsNew($value = TRUE) {
134 $this->enforceIsNew = $value;
135
136 return $this;
137 }
138
139 /**
140 * {@inheritdoc}
141 */
142 public function getEntityTypeId() {
143 return $this->entityTypeId;
144 }
145
146 /**
147 * {@inheritdoc}
148 */
149 public function bundle() {
150 return $this->entityTypeId;
151 }
152
153 /**
154 * {@inheritdoc}
155 */
156 public function label() {
157 $label = NULL;
158 $entity_type = $this->getEntityType();
159 if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
160 $label = call_user_func($label_callback, $this);
161 }
162 elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
163 $label = $this->{$label_key};
164 }
165 return $label;
166 }
167
168 /**
169 * {@inheritdoc}
170 */
171 public function urlInfo($rel = 'canonical', array $options = []) {
172 return $this->toUrl($rel, $options);
173 }
174
175 /**
176 * {@inheritdoc}
177 */
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()));
181 }
182
183 // The links array might contain URI templates set in annotations.
184 $link_templates = $this->linkTemplates();
185
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()) {
189 $rel = 'canonical';
190 }
191
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);
196 }
197 else {
198 $bundle = $this->bundle();
199 // A bundle-specific callback takes precedence over the generic one for
200 // the entity type.
201 $bundles = $this->entityManager()->getBundleInfo($this->getEntityTypeId());
202 if (isset($bundles[$bundle]['uri_callback'])) {
203 $uri_callback = $bundles[$bundle]['uri_callback'];
204 }
205 elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
206 $uri_callback = $entity_uri_callback;
207 }
208
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);
213 }
214 else {
215 throw new UndefinedLinkTemplateException("No link template '$rel' found for the '{$this->getEntityTypeId()}' entity type");
216 }
217 }
218
219 // Pass the entity data through as options, so that alter functions do not
220 // need to look up this entity again.
221 $uri
222 ->setOption('entity_type', $this->getEntityTypeId())
223 ->setOption('entity', $this);
224
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()];
230 }
231
232 $uri_options = $uri->getOptions();
233 $uri_options += $options;
234
235 return $uri->setOptions($uri_options);
236 }
237
238 /**
239 * {@inheritdoc}
240 */
241 public function hasLinkTemplate($rel) {
242 $link_templates = $this->linkTemplates();
243 return isset($link_templates[$rel]);
244 }
245
246 /**
247 * Gets an array link templates.
248 *
249 * @return array
250 * An array of link templates containing paths.
251 */
252 protected function linkTemplates() {
253 return $this->getEntityType()->getLinkTemplates();
254 }
255
256 /**
257 * {@inheritdoc}
258 */
259 public function link($text = NULL, $rel = 'canonical', array $options = []) {
260 return $this->toLink($text, $rel, $options)->toString();
261 }
262
263 /**
264 * {@inheritdoc}
265 */
266 public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
267 if (!isset($text)) {
268 $text = $this->label();
269 }
270 $url = $this->toUrl($rel);
271 $options += $url->getOptions();
272 $url->setOptions($options);
273 return new Link($text, $url);
274 }
275
276 /**
277 * {@inheritdoc}
278 */
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)) {
283 return '';
284 }
285
286 $uri = $this->toUrl($rel);
287 $options += $uri->getOptions();
288 $uri->setOptions($options);
289 return $uri->toString();
290 }
291
292 /**
293 * Gets an array of placeholders for this entity.
294 *
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.
298 *
299 * @param string $rel
300 * The link relationship type, for example: canonical or edit-form.
301 *
302 * @return array
303 * An array of URI placeholders.
304 */
305 protected function urlRouteParameters($rel) {
306 $uri_route_parameters = [];
307
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();
311 }
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();
315 }
316 if ($rel === 'revision' && $this instanceof RevisionableInterface) {
317 $uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
318 }
319
320 return $uri_route_parameters;
321 }
322
323 /**
324 * {@inheritdoc}
325 */
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
331 // relationships.
332 try {
333 $this->toUrl($link_relation_type)->toString(TRUE)->getGeneratedUrl();
334 }
335 catch (RouteNotFoundException $e) {
336 return FALSE;
337 }
338 return TRUE;
339 });
340 }
341
342 /**
343 * {@inheritdoc}
344 */
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);
350 }
351 return $this->entityManager()
352 ->getAccessControlHandler($this->entityTypeId)
353 ->access($this, $operation, $account, $return_as_object);
354 }
355
356 /**
357 * {@inheritdoc}
358 */
359 public function language() {
360 if ($key = $this->getEntityType()->getKey('langcode')) {
361 $langcode = $this->$key;
362 $language = $this->languageManager()->getLanguage($langcode);
363 if ($language) {
364 return $language;
365 }
366 }
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]);
370 return $language;
371 }
372
373 /**
374 * {@inheritdoc}
375 */
376 public function save() {
377 return $this->entityManager()->getStorage($this->entityTypeId)->save($this);
378 }
379
380 /**
381 * {@inheritdoc}
382 */
383 public function delete() {
384 if (!$this->isNew()) {
385 $this->entityManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);
386 }
387 }
388
389 /**
390 * {@inheritdoc}
391 */
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();
398
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();
402 }
403 return $duplicate;
404 }
405
406 /**
407 * {@inheritdoc}
408 */
409 public function getEntityType() {
410 return $this->entityManager()->getDefinition($this->getEntityTypeId());
411 }
412
413 /**
414 * {@inheritdoc}
415 */
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().");
422 }
423 }
424 }
425
426 /**
427 * {@inheritdoc}
428 */
429 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
430 $this->invalidateTagsOnSave($update);
431 }
432
433 /**
434 * {@inheritdoc}
435 */
436 public static function preCreate(EntityStorageInterface $storage, array &$values) {
437 }
438
439 /**
440 * {@inheritdoc}
441 */
442 public function postCreate(EntityStorageInterface $storage) {
443 }
444
445 /**
446 * {@inheritdoc}
447 */
448 public static function preDelete(EntityStorageInterface $storage, array $entities) {
449 }
450
451 /**
452 * {@inheritdoc}
453 */
454 public static function postDelete(EntityStorageInterface $storage, array $entities) {
455 static::invalidateTagsOnDelete($storage->getEntityType(), $entities);
456 }
457
458 /**
459 * {@inheritdoc}
460 */
461 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
462 }
463
464 /**
465 * {@inheritdoc}
466 */
467 public function referencedEntities() {
468 return [];
469 }
470
471 /**
472 * {@inheritdoc}
473 */
474 public function getCacheContexts() {
475 return $this->cacheContexts;
476 }
477
478 /**
479 * {@inheritdoc}
480 */
481 public function getCacheTagsToInvalidate() {
482 // @todo Add bundle-specific listing cache tag?
483 // https://www.drupal.org/node/2145751
484 if ($this->isNew()) {
485 return [];
486 }
487 return [$this->entityTypeId . ':' . $this->id()];
488 }
489
490 /**
491 * {@inheritdoc}
492 */
493 public function getCacheTags() {
494 if ($this->cacheTags) {
495 return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
496 }
497 return $this->getCacheTagsToInvalidate();
498 }
499
500 /**
501 * {@inheritdoc}
502 */
503 public function getCacheMaxAge() {
504 return $this->cacheMaxAge;
505 }
506
507 /**
508 * {@inheritdoc}
509 */
510 public static function load($id) {
511 $entity_manager = \Drupal::entityManager();
512 return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->load($id);
513 }
514
515 /**
516 * {@inheritdoc}
517 */
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);
521 }
522
523 /**
524 * {@inheritdoc}
525 */
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);
529 }
530
531 /**
532 * Invalidates an entity's cache tags upon save.
533 *
534 * @param bool $update
535 * TRUE if the entity has been updated, or FALSE if it has been inserted.
536 */
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']);
546 }
547 if ($update) {
548 // An existing entity was updated, also invalidate its unique cache tag.
549 $tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
550 }
551 Cache::invalidateTags($tags);
552 }
553
554 /**
555 * Invalidates an entity's cache tags upon delete.
556 *
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.
561 */
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());
571 }
572 Cache::invalidateTags($tags);
573 }
574
575 /**
576 * {@inheritdoc}
577 */
578 public function getOriginalId() {
579 // By default, entities do not support renames and do not have original IDs.
580 return NULL;
581 }
582
583 /**
584 * {@inheritdoc}
585 */
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
589 // as no longer new.
590 if ($id !== NULL) {
591 $this->enforceIsNew(FALSE);
592 }
593
594 return $this;
595 }
596
597 /**
598 * {@inheritdoc}
599 */
600 public function toArray() {
601 return [];
602 }
603
604 /**
605 * {@inheritdoc}
606 */
607 public function getTypedData() {
608 if (!isset($this->typedData)) {
609 $class = \Drupal::typedDataManager()->getDefinition('entity')['class'];
610 $this->typedData = $class::createFromEntity($this);
611 }
612 return $this->typedData;
613 }
614
615 /**
616 * {@inheritdoc}
617 */
618 public function __sleep() {
619 $this->typedData = NULL;
620 return $this->traitSleep();
621 }
622
623 /**
624 * {@inheritdoc}
625 */
626 public function getConfigDependencyKey() {
627 return $this->getEntityType()->getConfigDependencyKey();
628 }
629
630 /**
631 * {@inheritdoc}
632 */
633 public function getConfigDependencyName() {
634 return $this->getEntityTypeId() . ':' . $this->bundle() . ':' . $this->uuid();
635 }
636
637 /**
638 * {@inheritdoc}
639 */
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();
644 }
645
646 }