EntityManager.php 53.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
<?php

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

namespace Drupal\Core\Entity;

10
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
11
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
12
use Drupal\Component\Utility\SafeMarkup;
13
use Drupal\Core\Cache\Cache;
14
use Drupal\Core\Cache\CacheBackendInterface;
15
use Drupal\Core\Config\Entity\ConfigEntityType;
16
use Drupal\Core\DependencyInjection\ClassResolverInterface;
17
18
use Drupal\Core\Entity\Exception\AmbiguousEntityClassException;
use Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException;
19
use Drupal\Core\Extension\ModuleHandlerInterface;
20
use Drupal\Core\Field\BaseFieldDefinition;
21
use Drupal\Core\Field\FieldDefinitionInterface;
22
23
use Drupal\Core\Field\FieldStorageDefinitionEvent;
use Drupal\Core\Field\FieldStorageDefinitionEvents;
24
25
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionListenerInterface;
26
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
27
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
28
use Drupal\Core\Language\LanguageInterface;
29
use Drupal\Core\Language\LanguageManagerInterface;
30
use Drupal\Core\Plugin\DefaultPluginManager;
31
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
32
use Drupal\Core\StringTranslation\StringTranslationTrait;
33
use Drupal\Core\StringTranslation\TranslationInterface;
34
use Drupal\Core\TypedData\TranslatableInterface;
35
use Drupal\Core\TypedData\TypedDataManager;
36
37
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
38
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
39
40
41
42

/**
 * Manages entity type plugin definitions.
 *
43
 * Each entity type definition array is set in the entity type's
44
 * annotation and altered by hook_entity_type_alter().
45
46
 *
 * The defaults for the plugin definition are provided in
47
 * \Drupal\Core\Entity\EntityManagerInterface::defaults.
48
 *
49
50
 * @see \Drupal\Core\Entity\Annotation\EntityType
 * @see \Drupal\Core\Entity\EntityInterface
51
 * @see \Drupal\Core\Entity\EntityTypeInterface
52
 * @see hook_entity_type_alter()
53
 */
54
class EntityManager extends DefaultPluginManager implements EntityManagerInterface, ContainerAwareInterface {
55
56

  use ContainerAwareTrait;
57
  use StringTranslationTrait;
58

59
60
61
62
63
64
65
  /**
   * Extra fields by bundle.
   *
   * @var array
   */
  protected $extraFields = array();

66
  /**
67
   * Contains instantiated handlers keyed by handler type and entity type.
68
69
70
   *
   * @var array
   */
71
  protected $handlers = array();
72

73
  /**
74
   * Static cache of base field definitions.
75
76
77
   *
   * @var array
   */
78
  protected $baseFieldDefinitions;
79
80
81
82
83
84
85
86

  /**
   * Static cache of field definitions per bundle and entity type.
   *
   * @var array
   */
  protected $fieldDefinitions;

87
88
89
90
  /**
   * Static cache of field storage definitions per entity type.
   *
   * Elements of the array:
91
   *  - $entity_type_id: \Drupal\Core\Field\BaseFieldDefinition[]
92
93
94
95
96
   *
   * @var array
   */
  protected $fieldStorageDefinitions;

97
98
99
100
101
102
103
  /**
   * The string translationManager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

104
105
106
107
108
109
110
  /**
   * The class resolver.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

111
112
113
114
115
116
117
  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManager
   */
  protected $typedDataManager;

118
119
120
121
122
123
124
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

125
  /**
126
   * The keyvalue factory.
127
   *
128
   * @var \Drupal\Core\KeyValueStore\KeyValueFactoryInterface
129
   */
130
  protected $keyValueFactory;
131

132
133
134
135
136
137
138
  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

139
  /**
140
141
142
143
144
145
   * Static cache of bundle information.
   *
   * @var array
   */
  protected $bundleInfo;

146
147
148
149
150
151
152
  /**
   * Static cache of display modes information.
   *
   * @var array
   */
  protected $displayModeInfo = array();

153
154
155
156
157
158
159
160
161
162
  /**
   * An array keyed by entity type. Each value is an array whose keys are
   * field names and whose value is an array with two entries:
   *   - type: The field type.
   *   - bundles: The bundles in which the field appears.
   *
   * @return array
   */
  protected $fieldMap = array();

163
164
165
166
167
168
169
170
171
172
  /**
   * An array keyed by field type. Each value is an array whose key are entity
   * types including arrays in the same form that $fieldMap.
   *
   * It helps access the mapping between types and fields by the field type.
   *
   * @var array
   */
  protected $fieldMapByFieldType = array();

173
174
175
176
177
178
179
  /**
   * Contains cached mappings of class names to entity types.
   *
   * @var array
   */
  protected $classNameEntityTypeMap = array();

180
181
  /**
   * Constructs a new Entity plugin manager.
182
   *
183
184
185
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
186
187
188
189
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend to use.
190
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
191
   *   The language manager.
192
193
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
   *   The string translationManager.
194
195
   * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
   *   The class resolver.
196
197
   * @param \Drupal\Core\TypedData\TypedDataManager $typed_data_manager
   *   The typed data manager.
198
199
   * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
   *   The keyvalue factory.
200
201
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
202
   */
203
  public function __construct(\Traversable $namespaces, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, TranslationInterface $translation_manager, ClassResolverInterface $class_resolver, TypedDataManager $typed_data_manager, KeyValueFactoryInterface $key_value_factory, EventDispatcherInterface $event_dispatcher) {
204
    parent::__construct('Entity', $namespaces, $module_handler, 'Drupal\Core\Entity\EntityInterface');
205

206
    $this->setCacheBackend($cache, 'entity_type', array('entity_types'));
207
    $this->alterInfo('entity_type');
208

209
    $this->discovery = new AnnotatedClassDiscovery('Entity', $namespaces, 'Drupal\Core\Entity\Annotation\EntityType');
210
    $this->languageManager = $language_manager;
211
    $this->translationManager = $translation_manager;
212
    $this->classResolver = $class_resolver;
213
    $this->typedDataManager = $typed_data_manager;
214
    $this->keyValueFactory = $key_value_factory;
215
    $this->eventDispatcher = $event_dispatcher;
216
217
  }

218
219
220
221
222
  /**
   * {@inheritdoc}
   */
  public function clearCachedDefinitions() {
    parent::clearCachedDefinitions();
223
224
    $this->clearCachedBundles();
    $this->clearCachedFieldDefinitions();
225
    $this->classNameEntityTypeMap = array();
226
    $this->handlers = array();
227
228
  }

229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
  /**
   * {@inheritdoc}
   */
  protected function findDefinitions() {
    $definitions = $this->discovery->getDefinitions();

    // Directly call the hook implementations to pass the definitions to them
    // by reference, so new entity types can be added.
    foreach ($this->moduleHandler->getImplementations('entity_type_build') as $module) {
      $function = $module . '_' . 'entity_type_build';
      $function($definitions);
    }
    foreach ($definitions as $plugin_id => $definition) {
      $this->processDefinition($definition, $plugin_id);
    }
    if ($this->alterHook) {
      $this->moduleHandler->alter($this->alterHook, $definitions);
    }
    return $definitions;
  }

250
  /**
251
   * {@inheritdoc}
252
   */
253
254
  public function getDefinition($entity_type_id, $exception_on_invalid = TRUE) {
    if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
255
      return $entity_type;
256
    }
257
258
259
260
    elseif (!$exception_on_invalid) {
      return NULL;
    }

261
    throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));
262
263
  }

264
  /**
265
   * {@inheritdoc}
266
   */
267
  public function hasHandler($entity_type, $handler_type) {
268
    if ($definition = $this->getDefinition($entity_type, FALSE)) {
269
      return $definition->hasHandlerClass($handler_type);
270
    }
271
    return FALSE;
272
273
274
  }

  /**
275
   * {@inheritdoc}
276
   */
277
  public function getStorage($entity_type) {
278
    return $this->getHandler($entity_type, 'storage');
279
280
281
  }

  /**
282
   * {@inheritdoc}
283
   */
284
  public function getListBuilder($entity_type) {
285
    return $this->getHandler($entity_type, 'list_builder');
286
287
288
  }

  /**
289
   * {@inheritdoc}
290
   */
291
  public function getFormObject($entity_type, $operation) {
292
    if (!isset($this->handlers['form'][$operation][$entity_type])) {
293
294
295
      if (!$class = $this->getDefinition($entity_type, TRUE)->getFormClass($operation)) {
        throw new InvalidPluginDefinitionException($entity_type, sprintf('The "%s" entity type did not specify a "%s" form class.', $entity_type, $operation));
      }
296

297
      $form_object = $this->classResolver->getInstanceFromDefinition($class);
298

299
      $form_object
300
        ->setStringTranslation($this->translationManager)
301
        ->setModuleHandler($this->moduleHandler)
302
        ->setEntityManager($this)
303
        ->setOperation($operation);
304
      $this->handlers['form'][$operation][$entity_type] = $form_object;
305
    }
306
    return $this->handlers['form'][$operation][$entity_type];
307
308
  }

309
310
311
312
313
314
315
316
317
318
319
320
321
322
  /**
   * {@inheritdoc}
   */
  public function getRouteProviders($entity_type) {
    if (!isset($this->handlers['route_provider'][$entity_type])) {
      $route_provider_classes = $this->getDefinition($entity_type, TRUE)->getRouteProviderClasses();

      foreach ($route_provider_classes as $type => $class) {
        $this->handlers['route_provider'][$entity_type][$type] = $this->createHandlerInstance($class, $this->getDefinition($entity_type));
      }
    }
    return isset($this->handlers['route_provider'][$entity_type]) ? $this->handlers['route_provider'][$entity_type] : [];
  }

323
  /**
324
   * {@inheritdoc}
325
   */
326
  public function getViewBuilder($entity_type) {
327
    return $this->getHandler($entity_type, 'view_builder');
328
329
330
  }

  /**
331
   * {@inheritdoc}
332
   */
333
  public function getAccessControlHandler($entity_type) {
334
    return $this->getHandler($entity_type, 'access');
335
336
337
  }

  /**
338
   * {@inheritdoc}
339
   */
340
341
  public function getHandler($entity_type, $handler_type) {
    if (!isset($this->handlers[$handler_type][$entity_type])) {
342
      $definition = $this->getDefinition($entity_type);
343
      $class = $definition->getHandlerClass($handler_type);
344
      if (!$class) {
345
        throw new InvalidPluginDefinitionException($entity_type, sprintf('The "%s" entity type did not specify a %s handler.', $entity_type, $handler_type));
346
      }
347
      $this->handlers[$handler_type][$entity_type] = $this->createHandlerInstance($class, $definition);
348
    }
349
    return $this->handlers[$handler_type][$entity_type];
350
351
  }

352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
  /**
   * {@inheritdoc}
   */
  public function createHandlerInstance($class, EntityTypeInterface $definition = null) {
    if (is_subclass_of($class, 'Drupal\Core\Entity\EntityHandlerInterface')) {
      $handler = $class::createInstance($this->container, $definition);
    }
    else {
      $handler = new $class($definition);
    }
    if (method_exists($handler, 'setModuleHandler')) {
      $handler->setModuleHandler($this->moduleHandler);
    }
    if (method_exists($handler, 'setStringTranslation')) {
      $handler->setStringTranslation($this->translationManager);
    }
    return $handler;
  }

371
  /**
372
   * {@inheritdoc}
373
   */
374
375
376
377
  public function getBaseFieldDefinitions($entity_type_id) {
    // Check the static cache.
    if (!isset($this->baseFieldDefinitions[$entity_type_id])) {
      // Not prepared, try to load from cache.
378
      $cid = 'entity_base_field_definitions:' . $entity_type_id . ':' . $this->languageManager->getCurrentLanguage()->getId();
379
      if ($cache = $this->cacheGet($cid)) {
380
        $this->baseFieldDefinitions[$entity_type_id] = $cache->data;
381
382
      }
      else {
383
384
        // Rebuild the definitions and put it into the cache.
        $this->baseFieldDefinitions[$entity_type_id] = $this->buildBaseFieldDefinitions($entity_type_id);
385
        $this->cacheSet($cid, $this->baseFieldDefinitions[$entity_type_id], Cache::PERMANENT, array('entity_types', 'entity_field_info'));
386
387
388
389
390
391
392
393
394
395
       }
     }
    return $this->baseFieldDefinitions[$entity_type_id];
  }

  /**
   * Builds base field definitions for an entity type.
   *
   * @param string $entity_type_id
   *   The entity type ID. Only entity types that implement
396
   *   \Drupal\Core\Entity\FieldableEntityInterface are supported.
397
398
399
400
401
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   An array of field definitions, keyed by field name.
   *
   * @throws \LogicException
402
403
   *   Thrown if a config entity type is given or if one of the entity keys is
   *   flagged as translatable.
404
405
406
407
   */
  protected function buildBaseFieldDefinitions($entity_type_id) {
    $entity_type = $this->getDefinition($entity_type_id);
    $class = $entity_type->getClass();
408
    $keys = array_filter($entity_type->getKeys());
409

410
411
    // Fail with an exception for non-fieldable entity types.
    if (!$entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
412
      throw new \LogicException(SafeMarkup::format('Getting the base fields is not supported for entity type @type.', array('@type' => $entity_type->getLabel())));
413
414
    }

415
416
    // Retrieve base field definitions.
    /** @var FieldStorageDefinitionInterface[] $base_field_definitions */
417
    $base_field_definitions = $class::baseFieldDefinitions($entity_type);
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436

    // Make sure translatable entity types are correctly defined.
    if ($entity_type->isTranslatable()) {
      // The langcode field should always be translatable if the entity type is.
      if (isset($keys['langcode']) && isset($base_field_definitions[$keys['langcode']])) {
        $base_field_definitions[$keys['langcode']]->setTranslatable(TRUE);
      }
      // A default_langcode field should always be defined.
      if (!isset($base_field_definitions[$keys['default_langcode']])) {
        $base_field_definitions[$keys['default_langcode']] = BaseFieldDefinition::create('boolean')
          ->setLabel($this->t('Default translation'))
          ->setDescription($this->t('A flag indicating whether this is the default translation.'))
          ->setTranslatable(TRUE)
          ->setRevisionable(TRUE)
          ->setDefaultValue(TRUE);
      }
    }

    // Assign base field definitions the entity type provider.
437
438
    $provider = $entity_type->getProvider();
    foreach ($base_field_definitions as $definition) {
439
440
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
441
      if ($definition instanceof BaseFieldDefinition) {
442
443
444
        $definition->setProvider($provider);
      }
    }
445

446
447
448
449
450
451
452
    // Retrieve base field definitions from modules.
    foreach ($this->moduleHandler->getImplementations('entity_base_field_info') as $module) {
      $module_definitions = $this->moduleHandler->invoke($module, 'entity_base_field_info', array($entity_type));
      if (!empty($module_definitions)) {
        // Ensure the provider key actually matches the name of the provider
        // defining the field.
        foreach ($module_definitions as $field_name => $definition) {
453
454
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
455
          if ($definition instanceof BaseFieldDefinition && $definition->getProvider() == NULL) {
456
457
458
459
460
461
            $definition->setProvider($module);
          }
          $base_field_definitions[$field_name] = $definition;
        }
      }
    }
462

463
464
    // Automatically set the field name, target entity type and bundle
    // for non-configurable fields.
465
    foreach ($base_field_definitions as $field_name => $base_field_definition) {
466
      if ($base_field_definition instanceof BaseFieldDefinition) {
467
468
        $base_field_definition->setName($field_name);
        $base_field_definition->setTargetEntityTypeId($entity_type_id);
469
        $base_field_definition->setTargetBundle(NULL);
470
471
472
473
474
475
      }
    }

    // Invoke alter hook.
    $this->moduleHandler->alter('entity_base_field_info', $base_field_definitions, $entity_type);

476
477
    // Ensure defined entity keys are there and have proper revisionable and
    // translatable values.
478
479
    foreach (array_intersect_key($keys, array_flip(['id', 'revision', 'uuid', 'bundle'])) as $key => $field_name) {
      if (!isset($base_field_definitions[$field_name])) {
480
        throw new \LogicException(SafeMarkup::format('The @field field definition does not exist and it is used as @key entity key.', array(
481
          '@field' => $field_name,
482
483
484
485
          '@key' => $key,
        )));
      }
      if ($base_field_definitions[$field_name]->isRevisionable()) {
486
        throw new \LogicException(SafeMarkup::format('The @field field cannot be revisionable as it is used as @key entity key.', array(
487
488
489
          '@field' => $base_field_definitions[$field_name]->getLabel(),
          '@key' => $key,
        )));
490
      }
491
      if ($base_field_definitions[$field_name]->isTranslatable()) {
492
        throw new \LogicException(SafeMarkup::format('The @field field cannot be translatable as it is used as @key entity key.', array(
493
494
495
          '@field' => $base_field_definitions[$field_name]->getLabel(),
          '@key' => $key,
        )));
496
497
      }
    }
498
499
500

    // Make sure translatable entity types define the "langcode" field properly.
    if ($entity_type->isTranslatable() && (!isset($keys['langcode']) || !isset($base_field_definitions[$keys['langcode']]) || !$base_field_definitions[$keys['langcode']]->isTranslatable())) {
501
      throw new \LogicException(SafeMarkup::format('The @entity_type entity type cannot be translatable as it does not define a translatable "langcode" field.', array('@entity_type' => $entity_type->getLabel())));
502
503
    }

504
505
506
507
508
509
510
511
512
513
    return $base_field_definitions;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldDefinitions($entity_type_id, $bundle) {
    if (!isset($this->fieldDefinitions[$entity_type_id][$bundle])) {
      $base_field_definitions = $this->getBaseFieldDefinitions($entity_type_id);
      // Not prepared, try to load from cache.
514
      $cid = 'entity_bundle_field_definitions:' . $entity_type_id . ':' . $bundle . ':' . $this->languageManager->getCurrentLanguage()->getId();
515
      if ($cache = $this->cacheGet($cid)) {
516
517
518
519
        $bundle_field_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
520
        $bundle_field_definitions = $this->buildBundleFieldDefinitions($entity_type_id, $bundle, $base_field_definitions);
521
        $this->cacheSet($cid, $bundle_field_definitions, Cache::PERMANENT, array('entity_types', 'entity_field_info'));
522
523
524
525
526
527
      }
      // Field definitions consist of the bundle specific overrides and the
      // base fields, merge them together. Use array_replace() to replace base
      // fields with by bundle overrides and keep them in order, append
      // additional by bundle fields.
      $this->fieldDefinitions[$entity_type_id][$bundle] = array_replace($base_field_definitions, $bundle_field_definitions);
528
    }
529
530
531
532
533
534
535
536
    return $this->fieldDefinitions[$entity_type_id][$bundle];
  }

  /**
   * Builds field definitions for a specific bundle within an entity type.
   *
   * @param string $entity_type_id
   *   The entity type ID. Only entity types that implement
537
   *   \Drupal\Core\Entity\FieldableEntityInterface are supported.
538
539
540
541
542
543
544
545
546
   * @param string $bundle
   *   The bundle.
   * @param \Drupal\Core\Field\FieldDefinitionInterface[] $base_field_definitions
   *   The list of base field definitions.
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   An array of bundle field definitions, keyed by field name. Does
   *   not include base fields.
   */
547
  protected function buildBundleFieldDefinitions($entity_type_id, $bundle, array $base_field_definitions) {
548
549
550
    $entity_type = $this->getDefinition($entity_type_id);
    $class = $entity_type->getClass();

551
552
    // Allow the entity class to provide bundle fields and bundle-specific
    // overrides of base fields.
553
    $bundle_field_definitions = $class::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions);
554
555
556
557
558
559
560
561
562
563
564
565
566

    // Load base field overrides from configuration. These take precedence over
    // base field overrides returned above.
    $base_field_override_ids = array_map(function($field_name) use ($entity_type_id, $bundle) {
      return $entity_type_id . '.' . $bundle . '.' . $field_name;
    }, array_keys($base_field_definitions));
    $base_field_overrides = $this->getStorage('base_field_override')->loadMultiple($base_field_override_ids);
    foreach ($base_field_overrides as $base_field_override) {
      /** @var \Drupal\Core\Field\Entity\BaseFieldOverride $base_field_override */
      $field_name = $base_field_override->getName();
      $bundle_field_definitions[$field_name] = $base_field_override;
    }

567
568
    $provider = $entity_type->getProvider();
    foreach ($bundle_field_definitions as $definition) {
569
570
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
571
      if ($definition instanceof BaseFieldDefinition) {
572
573
574
        $definition->setProvider($provider);
      }
    }
575

576
577
578
579
580
581
582
    // Retrieve base field definitions from modules.
    foreach ($this->moduleHandler->getImplementations('entity_bundle_field_info') as $module) {
      $module_definitions = $this->moduleHandler->invoke($module, 'entity_bundle_field_info', array($entity_type, $bundle, $base_field_definitions));
      if (!empty($module_definitions)) {
        // Ensure the provider key actually matches the name of the provider
        // defining the field.
        foreach ($module_definitions as $field_name => $definition) {
583
584
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
585
          if ($definition instanceof BaseFieldDefinition) {
586
587
588
589
590
591
            $definition->setProvider($module);
          }
          $bundle_field_definitions[$field_name] = $definition;
        }
      }
    }
592

593
594
    // Automatically set the field name, target entity type and bundle
    // for non-configurable fields.
595
    foreach ($bundle_field_definitions as $field_name => $field_definition) {
596
      if ($field_definition instanceof BaseFieldDefinition) {
597
598
        $field_definition->setName($field_name);
        $field_definition->setTargetEntityTypeId($entity_type_id);
599
        $field_definition->setTargetBundle($bundle);
600
601
      }
    }
602
603
604
605
606

    // Invoke 'per bundle' alter hook.
    $this->moduleHandler->alter('entity_bundle_field_info', $bundle_field_definitions, $entity_type, $bundle);

    return $bundle_field_definitions;
607
608
  }

609
610
611
612
613
614
615
616
617
618
619
620
621
  /**
   * {@inheritdoc}
   */
  public function getFieldStorageDefinitions($entity_type_id) {
    if (!isset($this->fieldStorageDefinitions[$entity_type_id])) {
      $this->fieldStorageDefinitions[$entity_type_id] = array();
      // Add all non-computed base fields.
      foreach ($this->getBaseFieldDefinitions($entity_type_id) as $field_name => $definition) {
        if (!$definition->isComputed()) {
          $this->fieldStorageDefinitions[$entity_type_id][$field_name] = $definition;
        }
      }
      // Not prepared, try to load from cache.
622
      $cid = 'entity_field_storage_definitions:' . $entity_type_id . ':' . $this->languageManager->getCurrentLanguage()->getId();
623
      if ($cache = $this->cacheGet($cid)) {
624
625
626
627
628
        $field_storage_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
        $field_storage_definitions = $this->buildFieldStorageDefinitions($entity_type_id);
629
        $this->cacheSet($cid, $field_storage_definitions, Cache::PERMANENT, array('entity_types', 'entity_field_info'));
630
631
632
633
634
635
      }
      $this->fieldStorageDefinitions[$entity_type_id] += $field_storage_definitions;
    }
    return $this->fieldStorageDefinitions[$entity_type_id];
  }

636
637
638
639
640
641
642
  /**
   * {@inheritdoc}
   */
  public function getFieldMap() {
    if (!$this->fieldMap) {
      // Not prepared, try to load from cache.
      $cid = 'entity_field_map';
643
      if ($cache = $this->cacheGet($cid)) {
644
645
646
        $this->fieldMap = $cache->data;
      }
      else {
647
648
649
650
        // The field map is built in two steps. First, add all base fields, by
        // looping over all fieldable entity types. They always exist for all
        // bundles, and we do not expect to have so many different entity
        // types for this to become a bottleneck.
651
        foreach ($this->getDefinitions() as $entity_type_id => $entity_type) {
652
          if ($entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
            $bundles = array_keys($this->getBundleInfo($entity_type_id));
            foreach ($this->getBaseFieldDefinitions($entity_type_id) as $field_name => $base_field_definition) {
              $this->fieldMap[$entity_type_id][$field_name] = [
                'type' => $base_field_definition->getType(),
                'bundles' => array_combine($bundles, $bundles),
              ];
            }
          }
        }

        // In the second step, the per-bundle fields are added, based on the
        // persistent bundle field map stored in a key value collection. This
        // data is managed in the EntityManager::onFieldDefinitionCreate()
        // and EntityManager::onFieldDefinitionDelete() methods. Rebuilding this
        // information in the same way as base fields would not scale, as the
        // time to query would grow exponentially with more fields and bundles.
        // A cache would be deleted during cache clears, which is the only time
        // it is needed, so a key value collection is used.
        $bundle_field_maps = $this->keyValueFactory->get('entity.definitions.bundle_field_map')->getAll();
        foreach ($bundle_field_maps as $entity_type_id => $bundle_field_map) {
          foreach ($bundle_field_map as $field_name => $map_entry) {
            if (!isset($this->fieldMap[$entity_type_id][$field_name])) {
              $this->fieldMap[$entity_type_id][$field_name] = $map_entry;
            }
            else {
              $this->fieldMap[$entity_type_id][$field_name]['bundles'] += $map_entry['bundles'];
679
680
681
682
            }
          }
        }

683
        $this->cacheSet($cid, $this->fieldMap, Cache::PERMANENT, array('entity_types'));
684
685
686
687
688
      }
    }
    return $this->fieldMap;
  }

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
  /**
   * {@inheritdoc}
   */
  public function getFieldMapByFieldType($field_type) {
    if (!isset($this->fieldMapByFieldType[$field_type])) {
      $filtered_map = array();
      $map = $this->getFieldMap();
      foreach ($map as $entity_type => $fields) {
        foreach ($fields as $field_name => $field_info) {
          if ($field_info['type'] == $field_type) {
            $filtered_map[$entity_type][$field_name] = $field_info;
          }
        }
      }
      $this->fieldMapByFieldType[$field_type] = $filtered_map;
    }
    return $this->fieldMapByFieldType[$field_type];
  }

708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
  /**
   * {@inheritdoc}
   */
  public function onFieldDefinitionCreate(FieldDefinitionInterface $field_definition) {
    $entity_type_id = $field_definition->getTargetEntityTypeId();
    $bundle = $field_definition->getTargetBundle();
    $field_name = $field_definition->getName();

    // Notify the storage about the new field.
    $this->getStorage($entity_type_id)->onFieldDefinitionCreate($field_definition);

    // Update the bundle field map key value collection, add the new field.
    $bundle_field_map = $this->keyValueFactory->get('entity.definitions.bundle_field_map')->get($entity_type_id);
    if (!isset($bundle_field_map[$field_name])) {
      // This field did not exist yet, initialize it with the type and empty
      // bundle list.
      $bundle_field_map[$field_name] = [
        'type' => $field_definition->getType(),
        'bundles' => [],
      ];
    }
    $bundle_field_map[$field_name]['bundles'][$bundle] = $bundle;
    $this->keyValueFactory->get('entity.definitions.bundle_field_map')->set($entity_type_id, $bundle_field_map);

    // Delete the cache entry.
    $this->cacheBackend->delete('entity_field_map');

    // If the field map is initialized, update it as well, so that calls to it
    // do not have to rebuild it again.
    if ($this->fieldMap) {
      if (!isset($this->fieldMap[$entity_type_id][$field_name])) {
        // This field did not exist yet, initialize it with the type and empty
        // bundle list.
        $this->fieldMap[$entity_type_id][$field_name] = [
          'type' => $field_definition->getType(),
          'bundles' => [],
        ];
      }
      $this->fieldMap[$entity_type_id][$field_name]['bundles'][$bundle] = $bundle;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldDefinitionUpdate(FieldDefinitionInterface $field_definition, FieldDefinitionInterface $original) {
    // Notify the storage about the updated field.
    $this->getStorage($field_definition->getTargetEntityTypeId())->onFieldDefinitionUpdate($field_definition, $original);
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) {
    $entity_type_id = $field_definition->getTargetEntityTypeId();
    $bundle = $field_definition->getTargetBundle();
    $field_name = $field_definition->getName();

    // Notify the storage about the field deletion.
    $this->getStorage($entity_type_id)->onFieldDefinitionDelete($field_definition);

    // Unset the bundle from the bundle field map key value collection.
    $bundle_field_map = $this->keyValueFactory->get('entity.definitions.bundle_field_map')->get($entity_type_id);
    unset($bundle_field_map[$field_name]['bundles'][$bundle]);
    if (empty($bundle_field_map[$field_name]['bundles'])) {
      // If there are no bundles left, remove the field from the map.
      unset($bundle_field_map[$field_name]);
    }
    $this->keyValueFactory->get('entity.definitions.bundle_field_map')->set($entity_type_id, $bundle_field_map);

    // Delete the cache entry.
    $this->cacheBackend->delete('entity_field_map');

    // If the field map is initialized, update it as well, so that calls to it
    // do not have to rebuild it again.
    if ($this->fieldMap) {
      unset($this->fieldMap[$entity_type_id][$field_name]['bundles'][$bundle]);
      if (empty($this->fieldMap[$entity_type_id][$field_name]['bundles'])) {
        unset($this->fieldMap[$entity_type_id][$field_name]);
      }
    }
  }

791
792
793
794
795
  /**
   * Builds field storage definitions for an entity type.
   *
   * @param string $entity_type_id
   *   The entity type ID. Only entity types that implement
796
   *   \Drupal\Core\Entity\FieldableEntityInterface are supported
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
   *
   * @return \Drupal\Core\Field\FieldStorageDefinitionInterface[]
   *   An array of field storage definitions, keyed by field name.
   */
  protected function buildFieldStorageDefinitions($entity_type_id) {
    $entity_type = $this->getDefinition($entity_type_id);
    $field_definitions = array();

    // Retrieve base field definitions from modules.
    foreach ($this->moduleHandler->getImplementations('entity_field_storage_info') as $module) {
      $module_definitions = $this->moduleHandler->invoke($module, 'entity_field_storage_info', array($entity_type));
      if (!empty($module_definitions)) {
        // Ensure the provider key actually matches the name of the provider
        // defining the field.
        foreach ($module_definitions as $field_name => $definition) {
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
814
          if ($definition instanceof BaseFieldDefinition) {
815
816
817
818
819
820
821
822
823
824
825
826
827
            $definition->setProvider($module);
          }
          $field_definitions[$field_name] = $definition;
        }
      }
    }

    // Invoke alter hook.
    $this->moduleHandler->alter('entity_field_storage_info', $field_definitions, $entity_type);

    return $field_definitions;
  }

828
  /**
829
   * {@inheritdoc}
830
831
   */
  public function clearCachedFieldDefinitions() {
832
833
    $this->baseFieldDefinitions = array();
    $this->fieldDefinitions = array();
834
    $this->fieldStorageDefinitions = array();
835
    $this->fieldMap = array();
836
    $this->fieldMapByFieldType = array();
837
838
    $this->displayModeInfo = array();
    $this->extraFields = array();
839
    Cache::invalidateTags(array('entity_field_info'));
840
841
842
843
844
845
846
847
848
849
    // The typed data manager statically caches prototype objects with injected
    // definitions, clear those as well.
    $this->typedDataManager->clearCachedDefinitions();
  }

  /**
   * {@inheritdoc}
   */
  public function clearCachedBundles() {
    $this->bundleInfo = array();
850
    Cache::invalidateTags(array('entity_bundles'));
851
852
    // Entity bundles are exposed as data types, clear that cache too.
    $this->typedDataManager->clearCachedDefinitions();
853
854
  }

855
  /**
856
   * {@inheritdoc}
857
858
859
860
861
862
863
   */
  public function getBundleInfo($entity_type) {
    $bundle_info = $this->getAllBundleInfo();
    return isset($bundle_info[$entity_type]) ? $bundle_info[$entity_type] : array();
  }

  /**
864
   * {@inheritdoc}
865
866
   */
  public function getAllBundleInfo() {
867
    if (empty($this->bundleInfo)) {
868
      $langcode = $this->languageManager->getCurrentLanguage()->getId();
869
      if ($cache = $this->cacheGet("entity_bundle_info:$langcode")) {
870
871
872
873
        $this->bundleInfo = $cache->data;
      }
      else {
        $this->bundleInfo = $this->moduleHandler->invokeAll('entity_bundle_info');
874
875
        // First look for entity types that act as bundles for others, load them
        // and add them as bundles.
876
        foreach ($this->getDefinitions() as $type => $entity_type) {
877
878
879
880
881
882
883
884
          if ($entity_type->getBundleOf()) {
            foreach ($this->getStorage($type)->loadMultiple() as $entity) {
              $this->bundleInfo[$entity_type->getBundleOf()][$entity->id()]['label'] = $entity->label();
            }
          }
        }
        foreach ($this->getDefinitions() as $type => $entity_type) {
          // If no bundles are provided, use the entity type name and label.
885
          if (!isset($this->bundleInfo[$type])) {
886
            $this->bundleInfo[$type][$type]['label'] = $entity_type->getLabel();
887
888
889
          }
        }
        $this->moduleHandler->alter('entity_bundle_info', $this->bundleInfo);
890
        $this->cacheSet("entity_bundle_info:$langcode", $this->bundleInfo, Cache::PERMANENT, array('entity_types', 'entity_bundles'));
891
892
893
894
895
896
      }
    }

    return $this->bundleInfo;
  }

897
898
899
900
901
902
903
904
905
906
907
908
  /**
   * {@inheritdoc}
   */
  public function getExtraFields($entity_type_id, $bundle) {
    // Read from the "static" cache.
    if (isset($this->extraFields[$entity_type_id][$bundle])) {
      return $this->extraFields[$entity_type_id][$bundle];
    }

    // Read from the persistent cache. Since hook_entity_extra_field_info() and
    // hook_entity_extra_field_info_alter() might contain t() calls, we cache
    // per language.
909
    $cache_id = 'entity_bundle_extra_fields:' . $entity_type_id . ':' . $bundle . ':' . $this->languageManager->getCurrentLanguage()->getId();
910
    $cached = $this->cacheGet($cache_id);
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
    if ($cached) {
      $this->extraFields[$entity_type_id][$bundle] = $cached->data;
      return $this->extraFields[$entity_type_id][$bundle];
    }

    $extra = $this->moduleHandler->invokeAll('entity_extra_field_info');
    $this->moduleHandler->alter('entity_extra_field_info', $extra);
    $info = isset($extra[$entity_type_id][$bundle]) ? $extra[$entity_type_id][$bundle] : array();
    $info += array(
      'form' => array(),
      'display' => array(),
    );

    // Store in the 'static' and persistent caches.
    $this->extraFields[$entity_type_id][$bundle] = $info;
926
    $this->cacheSet($cache_id, $info, Cache::PERMANENT, array(
927
      'entity_field_info',
928
929
930
931
932
    ));

    return $this->extraFields[$entity_type_id][$bundle];
  }

933
  /**
934
   * {@inheritdoc}
935
   */
936
  public function getEntityTypeLabels($group = FALSE) {
937
    $options = array();
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
    $definitions = $this->getDefinitions();

    foreach ($definitions as $entity_type_id => $definition) {
      if ($group) {
        $options[$definition->getGroupLabel()][$entity_type_id] = $definition->getLabel();
      }
      else {
        $options[$entity_type_id] = $definition->getLabel();
      }
    }

    if ($group) {
      foreach ($options as &$group_options) {
        // Sort the list alphabetically by group label.
        array_multisort($group_options, SORT_ASC, SORT_NATURAL);
      }

      // Make sure that the 'Content' group is situated at the top.
      $content = $this->t('Content', array(), array('context' => 'Entity type group'));
      $options = array($content => $options[$content]) + $options;
958
959
960
961
962
    }

    return $options;
  }

963
964
965
966
967
968
  /**
   * {@inheritdoc}
   */
  public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
    $translation = $entity;

969
    if ($entity instanceof TranslatableInterface && count($entity->getTranslationLanguages()) > 1) {
970
      if (empty($langcode)) {
971
        $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
972
973
974
975
976
      }

      // Retrieve language fallback candidates to perform the entity language
      // negotiation.
      $context['data'] = $entity;
977
978
      $context += array('operation' => 'entity_view', 'langcode' => $langcode);
      $candidates = $this->languageManager->getFallbackCandidates($context);
979
980
981

      // Ensure the default language has the proper language code.
      $default_language = $entity->getUntranslated()->language();
982
      $candidates[$default_language->getId()] = LanguageInterface::LANGCODE_DEFAULT;
983
984
985
986
987
988
989
990
991
992
993
994
995

      // Return the most fitting entity translation.
      foreach ($candidates as $candidate) {
        if ($entity->hasTranslation($candidate)) {
          $translation = $entity->getTranslation($candidate);
          break;
        }
      }
    }

    return $translation;
  }

996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
  /**
   * {@inheritdoc}
   */
  public function getAllViewModes() {
    return $this->getAllDisplayModesByEntityType('view_mode');
  }

  /**
   * {@inheritdoc}
   */
  public function getViewModes($entity_type_id) {
    return $this->getDisplayModesByEntityType('view_mode', $entity_type_id);
  }

  /**
   * {@inheritdoc}
   */
  public function getAllFormModes() {
    return $this->getAllDisplayModesByEntityType('form_mode');
  }

  /**
   * {@inheritdoc}
   */
  public function getFormModes($entity_type_id) {
    return $this->getDisplayModesByEntityType('form_mode', $entity_type_id);
  }

  /**
1025
   * Gets the entity display mode info for all entity types.
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
   *
   * @param string $display_type
   *   The display type to be retrieved. It can be "view_mode" or "form_mode".
   *
   * @return array
   *   The display mode info for all entity types.
   */
  protected function getAllDisplayModesByEntityType($display_type) {
    if (!isset($this->displayModeInfo[$display_type])) {
      $key = 'entity_' . $display_type . '_info';
1036
      $entity_type_id = 'entity_' . $display_type;
1037
      $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_INTERFACE)->getId();
1038
      if ($cache = $this->cacheGet("$key:$langcode")) {
1039
1040
1041
1042
        $this->displayModeInfo[$display_type] = $cache->data;
      }
      else {
        $this->displayModeInfo[$display_type] = array();
1043
        foreach ($this->getStorage($entity_type_id)->loadMultiple() as $display_mode) {
1044
          list($display_mode_entity_type, $display_mode_name) = explode('.', $display_mode->id(), 2);
1045
          $this->displayModeInfo[$display_type][$display_mode_entity_type][$display_mode_name] = $display_mode->toArray();
1046
1047
        }
        $this->moduleHandler->alter($key, $this->displayModeInfo[$display_type]);
1048
        $this->cacheSet("$key:$langcode", $this->displayModeInfo[$display_type], CacheBackendInterface::CACHE_PERMANENT, array('entity_types', 'entity_field_info'));
1049
1050
1051
1052
1053
1054
1055
      }
    }

    return $this->displayModeInfo[$display_type];
  }

  /**
1056
   * Gets the entity display mode info for a specific entity type.
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
   *
   * @param string $display_type
   *   The display type to be retrieved. It can be "view_mode" or "form_mode".
   * @param string $entity_type_id
   *   The entity type whose display mode info should be returned.
   *
   * @return array
   *   The display mode info for a specific entity type.
   */
  protected function getDisplayModesByEntityType($display_type, $entity_type_id) {
    if (isset($this->displayModeInfo[$display_type][$entity_type_id])) {
      return $this->displayModeInfo[$display_type][$entity_type_id];
    }
    else {
      $display_modes = $this->getAllDisplayModesByEntityType($display_type);
      if (isset($display_modes[$entity_type_id])) {
        return $display_modes[$entity_type_id];
      }
    }
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getViewModeOptions($entity_type, $include_disabled = FALSE) {
    return $this->getDisplayModeOptions('view_mode', $entity_type, $include_disabled);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormModeOptions($entity_type, $include_disabled = FALSE) {
    return $this->getDisplayModeOptions('form_mode', $entity_type, $include_disabled);
  }

  /**
1094
   * Gets an array of display mode options.
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
   *
   * @param string $display_type
   *   The display type to be retrieved. It can be "view_mode" or "form_mode".
   * @param string $entity_type_id
   *   The entity type whose display mode options should be returned.
   * @param bool $include_disabled
   *   Force to include disabled display modes. Defaults to FALSE.
   *
   * @return array
   *   An array of display mode labels, keyed by the display mode ID.
   */
  protected function getDisplayModeOptions($display_type, $entity_type_id, $include_disabled = FALSE) {
    $options = array('default' => t('Default'));
    foreach ($this->getDisplayModesByEntityType($display_type, $entity_type_id) as $mode => $settings) {
      if (!empty($settings['status']) || $include_disabled) {
        $options[$mode] = $settings['label'];
      }
    }
    return $options;
  }

1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
  /**
   * {@inheritdoc}
   */
  public function loadEntityByUuid($entity_type_id, $uuid) {
    $entity_type = $this->getDefinition($entity_type_id);

    if (!$uuid_key = $entity_type->getKey('uuid')) {
      throw new EntityStorageException("Entity type $entity_type_id does not support UUIDs.");
    }

    $entities = $this->getStorage($entity_type_id)->loadByProperties(array($uuid_key => $uuid));

    return reset($entities);
  }

1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
  /**
   * {@inheritdoc}
   */
  public function loadEntityByConfigTarget($entity_type_id, $target) {
    $entity_type = $this->getDefinition($entity_type_id);

    // For configuration entities, the config target is given by the entity ID.
    // @todo Consider adding a method to allow entity types to indicate the
    //   target identifier key rather than hard-coding this check. Issue:
    //   https://www.drupal.org/node/2412983.
    if ($entity_type instanceof ConfigEntityType) {
      $entity = $this->getStorage($entity_type_id)->load($target);
    }

    // For content entities, the config target is given by the UUID.
    else {
      $entity = $this->loadEntityByUuid($entity_type_id, $target);
    }

    return $entity;
  }

1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
  /**
   * {@inheritdoc}
   */
  public function getEntityTypeFromClass($class_name) {

    // Check the already calculated classes first.
    if (isset($this->classNameEntityTypeMap[$class_name])) {
      return $this->classNameEntityTypeMap[$class_name];
    }

    $same_class = 0;
    $entity_type_id = NULL;
    foreach ($this->getDefinitions() as $entity_type) {
      if ($entity_type->getOriginalClass() == $class_name  || $entity_type->getClass() == $class_name) {
        $entity_type_id = $entity_type->id();
        if ($same_class++) {
          throw new AmbiguousEntityClassException($class_name);
        }
      }
    }

    // Return the matching entity type ID if there is one.
    if ($entity_type_id) {
      $this->classNameEntityTypeMap[$class_name] = $entity_type_id;
      return $entity_type_id;
    }

    throw new NoCorrespondingEntityClassException($class_name);
  }

1183
1184
1185
1186
  /**
   * {@inheritdoc}
   */
  public function onEntityTypeCreate(EntityTypeInterface $entity_type) {
1187
1188
    $entity_type_id = $entity_type->id();

1189
1190
    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
1191
    $storage = $this->getStorage($entity_type_id);
1192
1193
1194
    if ($storage instanceof EntityTypeListenerInterface) {
      $storage->onEntityTypeCreate($entity_type);
    }
1195

1196
1197
    $this->eventDispatcher->dispatch(EntityTypeEvents::CREATE, new EntityTypeEvent($entity_type));

1198
    $this->setLastInstalledDefinition($entity_type);
1199
    if ($entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
1200
1201
      $this->setLastInstalledFieldStorageDefinitions($entity_type_id, $this->getFieldStorageDefinitions($entity_type_id));
    }
1202
1203
1204
1205
1206
1207
  }

  /**
   * {@inheritdoc}
   */
  public function onEntityTypeUpdate(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
1208
1209
    $entity_type_id = $entity_type->id();

1210
1211
    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
1212
    $storage = $this->getStorage($entity_type_id);
1213
1214
1215
    if ($storage instanceof EntityTypeListenerInterface) {
      $storage->onEntityTypeUpdate($entity_type, $original);
    }
1216

1217
1218
    $this->eventDispatcher->dispatch(EntityTypeEvents::UPDATE, new EntityTypeEvent($entity_type, $original));

1219
    $this->setLastInstalledDefinition($entity_type);
1220
1221
1222
1223
1224
1225
  }

  /**
   * {@inheritdoc}
   */
  public function onEntityTypeDelete(EntityTypeInterface $entity_type) {
1226
1227
    $entity_type_id = $entity_type->id();