summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/Entity/Entity.php
blob: b69ba1dfb209b6e8807a724b49edd976231c325c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
<?php

/**
 * @file
 * Contains \Drupal\Core\Entity\Entity.
 */

namespace Drupal\Core\Entity;

use Drupal\Core\Cache\Cache;
use Drupal\Core\DependencyInjection\DependencySerialization;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\String;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\Exception\ConfigEntityIdLengthException;
use Drupal\Core\Entity\Exception\AmbiguousEntityClassException;
use Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException;
use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
use Drupal\Core\Language\Language;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;

/**
 * Defines a base entity class.
 */
abstract class Entity extends DependencySerialization implements EntityInterface {

  /**
   * The entity type.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * Boolean indicating whether the entity should be forced to be new.
   *
   * @var bool
   */
  protected $enforceIsNew;

  /**
   * Constructs an Entity object.
   *
   * @param array $values
   *   An array of values to set, keyed by property name. If the entity type
   *   has bundles, the bundle key has to be specified.
   * @param string $entity_type
   *   The type of the entity to create.
   */
  public function __construct(array $values, $entity_type) {
    $this->entityTypeId = $entity_type;
    // Set initial values.
    foreach ($values as $key => $value) {
      $this->$key = $value;
    }
  }

  /**
   * Returns the entity manager.
   *
   * @return \Drupal\Core\Entity\EntityManagerInterface
   */
  protected function entityManager() {
    return \Drupal::entityManager();
  }

  /**
   * Returns the language manager.
   *
   * @return \Drupal\Core\Language\LanguageManagerInterface
   */
  protected function languageManager() {
    return \Drupal::languageManager();
  }

  /**
   * Returns the UUID generator.
   *
   * @return \Drupal\Component\Uuid\UuidInterface
   */
  protected function uuidGenerator() {
    return \Drupal::service('uuid');
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
    return isset($this->id) ? $this->id : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function uuid() {
    return isset($this->uuid) ? $this->uuid : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function isNew() {
    return !empty($this->enforceIsNew) || !$this->id();
  }

  /**
   * {@inheritdoc}
   */
  public function enforceIsNew($value = TRUE) {
    $this->enforceIsNew = $value;

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityTypeId() {
    return $this->entityTypeId;
  }

  /**
   * {@inheritdoc}
   */
  public function bundle() {
    return $this->entityTypeId;
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    $label = NULL;
    $entity_type = $this->getEntityType();
    if (($label_callback = $entity_type->getLabelCallback()) && is_callable($label_callback)) {
      $label = call_user_func($label_callback, $this);
    }
    elseif (($label_key = $entity_type->getKey('label')) && isset($this->{$label_key})) {
      $label = $this->{$label_key};
    }
    return $label;
  }

  /**
   * {@inheritdoc}
   */
  public function urlInfo($rel = 'canonical') {
    if ($this->isNew()) {
      throw new EntityMalformedException(sprintf('The "%s" entity type has not been saved, and cannot have a URI.', $this->getEntityTypeId()));
    }

    // The links array might contain URI templates set in annotations.
    $link_templates = $this->linkTemplates();

    if (isset($link_templates[$rel])) {
      // If there is a template for the given relationship type, generate the path.
      $uri = new Url($link_templates[$rel], $this->urlRouteParameters($rel));
    }
    else {
      $bundle = $this->bundle();
      // A bundle-specific callback takes precedence over the generic one for
      // the entity type.
      $bundles = $this->entityManager()->getBundleInfo($this->getEntityTypeId());
      if (isset($bundles[$bundle]['uri_callback'])) {
        $uri_callback = $bundles[$bundle]['uri_callback'];
      }
      elseif ($entity_uri_callback = $this->getEntityType()->getUriCallback()) {
        $uri_callback = $entity_uri_callback;
      }

      // Invoke the callback to get the URI. If there is no callback, use the
      // default URI format.
      if (isset($uri_callback) && is_callable($uri_callback)) {
        $uri = call_user_func($uri_callback, $this);
      }
      else {
        throw new UndefinedLinkTemplateException(String::format('No link template "@rel" found for the "@entity_type" entity type', array(
          '@rel' => $rel,
          '@entity_type' => $this->getEntityTypeId(),
        )));
      }
    }

    // Pass the entity data to url() so that alter functions do not need to
    // look up this entity again.
    $uri
      ->setOption('entity_type', $this->getEntityTypeId())
      ->setOption('entity', $this);

    return $uri;
  }

  /**
   * {@inheritdoc}
   */
  public function getSystemPath($rel = 'canonical') {
    if ($this->hasLinkTemplate($rel) && $uri = $this->urlInfo($rel)) {
      return $uri->getInternalPath();
    }
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function hasLinkTemplate($rel) {
    $link_templates = $this->linkTemplates();
    return isset($link_templates[$rel]);
  }

  /**
   * Returns an array link templates.
   *
   * @return array
   *   An array of link templates containing route names.
   */
  protected function linkTemplates() {
    return $this->getEntityType()->getLinkTemplates();
  }

  /**
   * {@inheritdoc}
   */
  public function url($rel = 'canonical', $options = array()) {
    // While self::urlInfo() will throw an exception if the entity is new,
    // the expected result for a URL is always a string.
    if ($this->isNew() || !$this->hasLinkTemplate($rel)) {
      return '';
    }

    $uri = $this->urlInfo($rel);
    $options += $uri->getOptions();
    $uri->setOptions($options);
    return $uri->toString();
  }

  /**
   * Returns an array of placeholders for this entity.
   *
   * Individual entity classes may override this method to add additional
   * placeholders if desired. If so, they should be sure to replicate the
   * property caching logic.
   *
   * @param string $rel
   *   The link relationship type, for example: canonical or edit-form.
   *
   * @return array
   *   An array of URI placeholders.
   */
  protected function urlRouteParameters($rel) {
    // The entity ID is needed as a route parameter.
    $uri_route_parameters[$this->getEntityTypeId()] = $this->id();

    // The 'admin-form' link requires the bundle as a route parameter if the
    // entity type uses bundles.
    if ($rel == 'admin-form' && $this->getEntityType()->getBundleEntityType() != 'bundle') {
      $uri_route_parameters[$this->getEntityType()->getBundleEntityType()] = $this->bundle();
    }
    return $uri_route_parameters;
  }

  /**
   * {@inheritdoc}
   *
   * Returns a list of URI relationships supported by this entity.
   *
   * @return array
   *   An array of link relationships supported by this entity.
   */
  public function uriRelationships() {
    return array_keys($this->linkTemplates());
  }

  /**
   * {@inheritdoc}
   */
  public function access($operation, AccountInterface $account = NULL) {
    if ($operation == 'create') {
      return $this->entityManager()
        ->getAccessController($this->entityTypeId)
        ->createAccess($this->bundle(), $account);
    }
    return $this->entityManager()
      ->getAccessController($this->entityTypeId)
      ->access($this, $operation, Language::LANGCODE_DEFAULT, $account);
  }

  /**
   * {@inheritdoc}
   */
  public function language() {
    $language = $this->languageManager()->getLanguage($this->langcode);
    if (!$language) {
      // Make sure we return a proper language object.
      $language = new Language(array('id' => Language::LANGCODE_NOT_SPECIFIED));
    }
    return $language;
  }

  /**
   * {@inheritdoc}
   */
  public function save() {
    return $this->entityManager()->getStorage($this->entityTypeId)->save($this);
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {
    if (!$this->isNew()) {
      $this->entityManager()->getStorage($this->entityTypeId)->delete(array($this->id() => $this));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function createDuplicate() {
    $duplicate = clone $this;
    $entity_type = $this->getEntityType();
    // Reset the entity ID and indicate that this is a new entity.
    $duplicate->{$entity_type->getKey('id')} = NULL;
    $duplicate->enforceIsNew();

    // Check if the entity type supports UUIDs and generate a new one if so.
    if ($entity_type->hasKey('uuid')) {
      $duplicate->{$entity_type->getKey('uuid')} = $this->uuidGenerator()->generate();
    }
    return $duplicate;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityType() {
    return $this->entityManager()->getDefinition($this->getEntityTypeId());
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    // Check if this is an entity bundle.
    if ($this->getEntityType()->getBundleOf()) {
      // Throw an exception if the bundle ID is longer than 32 characters.
      if (Unicode::strlen($this->id()) > EntityTypeInterface::BUNDLE_MAX_LENGTH) {
        throw new ConfigEntityIdLengthException(String::format(
          'Attempt to create a bundle with an ID longer than @max characters: @id.', array(
            '@max' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
            '@id' => $this->id(),
          )
        ));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    $this->onSaveOrDelete();
    $this->invalidateTagsOnSave($update);
  }

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage, array &$values) {
  }

  /**
   * {@inheritdoc}
   */
  public function postCreate(EntityStorageInterface $storage) {
  }

  /**
   * {@inheritdoc}
   */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    self::invalidateTagsOnDelete($entities);
  }

  /**
   * {@inheritdoc}
   */
  public static function postLoad(EntityStorageInterface $storage, array &$entities) {
  }

  /**
   * {@inheritdoc}
   */
  public function referencedEntities() {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTag() {
    return array($this->entityTypeId => array($this->id()));
  }

  /**
   * {@inheritdoc}
   */
  public function getListCacheTags() {
    // @todo Add bundle-specific listing cache tag? https://drupal.org/node/2145751
    return array($this->entityTypeId . 's' => TRUE);
  }

  /**
   * {@inheritdoc}
   */
  public static function load($id) {
    return \Drupal::entityManager()->getStorage(static::getEntityTypeFromStaticClass())->load($id);
  }

  /**
   * {@inheritdoc}
   */
  public static function loadMultiple(array $ids = NULL) {
    return \Drupal::entityManager()->getStorage(static::getEntityTypeFromStaticClass())->loadMultiple($ids);
  }

  /**
   * Returns the entity type ID based on the class that is called on.
   *
   * Compares the class this is called on against the known entity classes
   * and returns the entity type ID of a direct match or a subclass as fallback,
   * to support entity type definitions that were altered.
   *
   * @return string
   *   The entity type ID.
   *
   * @throws \Drupal\Core\Entity\Exception\AmbiguousEntityClassException
   *   Thrown when multiple subclasses correspond to the called class.
   * @throws \Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException
   *   Thrown when no entity class corresponds to the called class.
   *
   * @see \Drupal\Core\Entity\Entity::load()
   * @see \Drupal\Core\Entity\Entity::loadMultiple()
   */
  protected static function getEntityTypeFromStaticClass() {
    $called_class = get_called_class();
    $subclasses = 0;
    $same_class = 0;
    $entity_type_id = NULL;
    $subclass_entity_type_id = NULL;
    foreach (\Drupal::entityManager()->getDefinitions() as $entity_type) {
      // Check if this is the same class, throw an exception if there is more
      // than one match.
      if ($entity_type->getClass() == $called_class) {
        $entity_type_id = $entity_type->id();
        if ($same_class++) {
          throw new AmbiguousEntityClassException($called_class);
        }
      }
      // Check for entity types that are subclasses of the called class, but
      // throw an exception if we have multiple matches.
      elseif (is_subclass_of($entity_type->getClass(), $called_class)) {
        $subclass_entity_type_id = $entity_type->id();
        if ($subclasses++) {
          throw new AmbiguousEntityClassException($called_class);
        }
      }
    }

    // Return the matching entity type ID or the subclass match if there is one
    // as a secondary priority.
    if ($entity_type_id) {
      return $entity_type_id;
    }
    if ($subclass_entity_type_id) {
      return $subclass_entity_type_id;
    }
    throw new NoCorrespondingEntityClassException($called_class);
  }

  /**
   * Acts on an entity after it was saved or deleted.
   */
  protected function onSaveOrDelete() {
    $referenced_entities = array(
      $this->getEntityTypeId() => array($this->id() => $this),
    );

    foreach ($this->referencedEntities() as $referenced_entity) {
      $referenced_entities[$referenced_entity->getEntityTypeId()][$referenced_entity->id()] = $referenced_entity;
    }

    foreach ($referenced_entities as $entity_type => $entities) {
      if ($this->entityManager()->hasController($entity_type, 'view_builder')) {
        $this->entityManager()->getViewBuilder($entity_type)->resetCache($entities);
      }
    }
  }

  /**
   * Invalidates an entity's cache tags upon save.
   *
   * @param bool $update
   *   TRUE if the entity has been updated, or FALSE if it has been inserted.
   */
  protected function invalidateTagsOnSave($update) {
    // An entity was created or updated: invalidate its list cache tags. (An
    // updated entity may start to appear in a listing because it now meets that
    // listing's filtering requirements. A newly created entity may start to
    // appear in listings because it did not exist before.)
    $tags = $this->getListCacheTags();
    if ($update) {
      // An existing entity was updated, also invalidate its unique cache tag.
      $tags = NestedArray::mergeDeep($tags, $this->getCacheTag());
      $this->onUpdateBundleEntity();
    }
    Cache::invalidateTags($tags);
  }

  /**
   * Invalidates an entity's cache tags upon delete.
   *
   * @param \Drupal\Core\Entity\EntityInterface[] $entities
   *   An array of entities.
   */
  protected static function invalidateTagsOnDelete(array $entities) {
    $tags = array();
    foreach ($entities as $entity) {
      // An entity was deleted: invalidate its own cache tag, but also its list
      // cache tags. (A deleted entity may cause changes in a paged list on
      // other pages than the one it's on. The one it's on is handled by its own
      // cache tag, but subsequent list pages would not be invalidated, hence we
      // must invalidate its list cache tags as well.)
      $tags = NestedArray::mergeDeepArray(array($tags, $entity->getCacheTag(), $entity->getListCacheTags()));
      $entity->onSaveOrDelete();
    }
    Cache::invalidateTags($tags);
  }

  /**
   * Acts on entities of which this entity is a bundle entity type.
   */
  protected function onUpdateBundleEntity() {
    // If this entity is a bundle entity type of another entity type, and we're
    // updating an existing entity, and that other entity type has a view
    // builder class, then invalidate the render cache of entities for which
    // this entity is a bundle.
    $bundle_of = $this->getEntityType()->getBundleOf();
    $entity_manager = \Drupal::entityManager();
    if ($bundle_of !== FALSE && $entity_manager->hasController($bundle_of, 'view_builder')) {
      $entity_manager->getViewBuilder($bundle_of)->resetCache();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getOriginalId() {
    // By default, entities do not support renames and do not have original IDs.
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function setOriginalId($id) {
    // By default, entities do not support renames and do not have original IDs.
    // If the specified ID is anything except NULL, this should mark this entity
    // as no longer new.
    if ($id !== NULL) {
      $this->enforceIsNew(FALSE);
    }

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function toArray() {
    return array();
  }

}