EntityManager.php 45.6 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\String;
13
use Drupal\Core\Cache\Cache;
14
use Drupal\Core\Cache\CacheBackendInterface;
15
use Drupal\Core\DependencyInjection\ClassResolverInterface;
16 17
use Drupal\Core\Entity\Exception\AmbiguousEntityClassException;
use Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException;
18
use Drupal\Core\Extension\ModuleHandlerInterface;
19 20 21
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionEvent;
use Drupal\Core\Field\FieldStorageDefinitionEvents;
22 23
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionListenerInterface;
24
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
25
use Drupal\Core\Language\LanguageInterface;
26
use Drupal\Core\Language\LanguageManagerInterface;
27
use Drupal\Core\Plugin\DefaultPluginManager;
28
use Drupal\Core\StringTranslation\StringTranslationTrait;
29
use Drupal\Core\StringTranslation\TranslationInterface;
30
use Drupal\Core\TypedData\TranslatableInterface;
31
use Drupal\Core\TypedData\TypedDataManager;
32 33
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
34
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
35 36 37 38

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

  use ContainerAwareTrait;
53
  use StringTranslationTrait;
54

55 56 57 58 59 60 61
  /**
   * Extra fields by bundle.
   *
   * @var array
   */
  protected $extraFields = array();

62
  /**
63
   * Contains instantiated handlers keyed by handler type and entity type.
64 65 66
   *
   * @var array
   */
67
  protected $handlers = array();
68

69
  /**
70
   * Static cache of base field definitions.
71 72 73
   *
   * @var array
   */
74
  protected $baseFieldDefinitions;
75 76 77 78 79 80 81 82

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

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

93 94 95 96 97 98 99
  /**
   * The string translationManager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

100 101 102 103 104 105 106
  /**
   * The class resolver.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

107 108 109 110 111 112 113
  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManager
   */
  protected $typedDataManager;

114 115 116 117 118 119 120
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

121 122 123 124 125 126 127
  /**
   * The keyvalue collection for tracking installed definitions.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $installedDefinitions;

128 129 130 131 132 133 134
  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

135
  /**
136 137 138 139 140 141
   * Static cache of bundle information.
   *
   * @var array
   */
  protected $bundleInfo;

142 143 144 145 146 147 148
  /**
   * Static cache of display modes information.
   *
   * @var array
   */
  protected $displayModeInfo = array();

149 150 151 152 153 154 155 156 157 158
  /**
   * 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();

159 160 161 162 163 164 165 166 167 168
  /**
   * 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();

169 170 171 172 173 174 175
  /**
   * Contains cached mappings of class names to entity types.
   *
   * @var array
   */
  protected $classNameEntityTypeMap = array();

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

202
    $this->setCacheBackend($cache, 'entity_type', array('entity_types'));
203
    $this->alterInfo('entity_type');
204

205
    $this->languageManager = $language_manager;
206
    $this->translationManager = $translation_manager;
207
    $this->classResolver = $class_resolver;
208
    $this->typedDataManager = $typed_data_manager;
209
    $this->installedDefinitions = $installed_definitions;
210
    $this->eventDispatcher = $event_dispatcher;
211 212
  }

213 214 215 216 217
  /**
   * {@inheritdoc}
   */
  public function clearCachedDefinitions() {
    parent::clearCachedDefinitions();
218 219
    $this->clearCachedBundles();
    $this->clearCachedFieldDefinitions();
220
    $this->classNameEntityTypeMap = array();
221
    $this->handlers = array();
222 223
  }

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  /**
   * {@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;
  }

245
  /**
246
   * {@inheritdoc}
247
   */
248 249
  public function getDefinition($entity_type_id, $exception_on_invalid = TRUE) {
    if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
250
      return $entity_type;
251
    }
252 253 254 255
    elseif (!$exception_on_invalid) {
      return NULL;
    }

256
    throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));
257 258
  }

259
  /**
260
   * {@inheritdoc}
261
   */
262
  public function hasHandler($entity_type, $handler_type) {
263
    if ($definition = $this->getDefinition($entity_type, FALSE)) {
264
      return $definition->hasHandlerClass($handler_type);
265
    }
266
    return FALSE;
267 268 269
  }

  /**
270
   * {@inheritdoc}
271
   */
272
  public function getStorage($entity_type) {
273
    return $this->getHandler($entity_type, 'storage');
274 275 276
  }

  /**
277
   * {@inheritdoc}
278
   */
279
  public function getListBuilder($entity_type) {
280
    return $this->getHandler($entity_type, 'list_builder');
281 282 283
  }

  /**
284
   * {@inheritdoc}
285
   */
286
  public function getFormObject($entity_type, $operation) {
287
    if (!isset($this->handlers['form'][$operation][$entity_type])) {
288 289 290
      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));
      }
291

292
      $form_object = $this->classResolver->getInstanceFromDefinition($class);
293

294
      $form_object
295
        ->setStringTranslation($this->translationManager)
296 297
        ->setModuleHandler($this->moduleHandler)
        ->setOperation($operation);
298
      $this->handlers['form'][$operation][$entity_type] = $form_object;
299
    }
300
    return $this->handlers['form'][$operation][$entity_type];
301 302 303
  }

  /**
304
   * {@inheritdoc}
305
   */
306
  public function getViewBuilder($entity_type) {
307
    return $this->getHandler($entity_type, 'view_builder');
308 309 310
  }

  /**
311
   * {@inheritdoc}
312
   */
313
  public function getAccessControlHandler($entity_type) {
314
    return $this->getHandler($entity_type, 'access');
315 316 317
  }

  /**
318
   * {@inheritdoc}
319
   */
320 321
  public function getHandler($entity_type, $handler_type) {
    if (!isset($this->handlers[$handler_type][$entity_type])) {
322
      $definition = $this->getDefinition($entity_type);
323
      $class = $definition->getHandlerClass($handler_type);
324
      if (!$class) {
325
        throw new InvalidPluginDefinitionException($entity_type, sprintf('The "%s" entity type did not specify a %s handler.', $entity_type, $handler_type));
326
      }
327
      $this->handlers[$handler_type][$entity_type] = $this->createHandlerInstance($class, $definition);
328
    }
329
    return $this->handlers[$handler_type][$entity_type];
330 331
  }

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
  /**
   * {@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;
  }

351
  /**
352
   * {@inheritdoc}
353
   */
354 355 356 357
  public function getBaseFieldDefinitions($entity_type_id) {
    // Check the static cache.
    if (!isset($this->baseFieldDefinitions[$entity_type_id])) {
      // Not prepared, try to load from cache.
358
      $cid = 'entity_base_field_definitions:' . $entity_type_id . ':' . $this->languageManager->getCurrentLanguage()->getId();
359
      if ($cache = $this->cacheBackend->get($cid)) {
360
        $this->baseFieldDefinitions[$entity_type_id] = $cache->data;
361 362
      }
      else {
363 364
        // Rebuild the definitions and put it into the cache.
        $this->baseFieldDefinitions[$entity_type_id] = $this->buildBaseFieldDefinitions($entity_type_id);
365
        $this->cacheBackend->set($cid, $this->baseFieldDefinitions[$entity_type_id], Cache::PERMANENT, array('entity_types', 'entity_field_info'));
366 367 368 369 370 371 372 373 374 375
       }
     }
    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
376
   *   \Drupal\Core\Entity\FieldableEntityInterface are supported.
377 378 379 380 381
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   An array of field definitions, keyed by field name.
   *
   * @throws \LogicException
382 383
   *   Thrown if a config entity type is given or if one of the entity keys is
   *   flagged as translatable.
384 385 386 387 388
   */
  protected function buildBaseFieldDefinitions($entity_type_id) {
    $entity_type = $this->getDefinition($entity_type_id);
    $class = $entity_type->getClass();

389 390
    // Fail with an exception for non-fieldable entity types.
    if (!$entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
391 392 393
      throw new \LogicException(String::format('Getting the base fields is not supported for entity type @type.', array('@type' => $entity_type->getLabel())));
    }

394
    // Retrieve base field definitions and assign them the entity type provider.
395
    $base_field_definitions = $class::baseFieldDefinitions($entity_type);
396 397
    $provider = $entity_type->getProvider();
    foreach ($base_field_definitions as $definition) {
398 399
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
400
      if ($definition instanceof BaseFieldDefinition) {
401 402 403
        $definition->setProvider($provider);
      }
    }
404

405 406 407 408 409 410 411
    // 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) {
412 413
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
414
          if ($definition instanceof BaseFieldDefinition && $definition->getProvider() == NULL) {
415 416 417 418 419 420
            $definition->setProvider($module);
          }
          $base_field_definitions[$field_name] = $definition;
        }
      }
    }
421

422 423
    // Automatically set the field name, target entity type and bundle
    // for non-configurable fields.
424
    foreach ($base_field_definitions as $field_name => $base_field_definition) {
425
      if ($base_field_definition instanceof BaseFieldDefinition) {
426 427
        $base_field_definition->setName($field_name);
        $base_field_definition->setTargetEntityTypeId($entity_type_id);
428
        $base_field_definition->setTargetBundle(NULL);
429 430 431 432 433 434
      }
    }

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

435 436 437 438 439 440 441 442 443
    // Ensure defined entity keys are there and have proper revisionable and
    // translatable values.
    $keys = array_filter($entity_type->getKeys() + array('langcode' => 'langcode'));
    foreach ($keys as $key => $field_name) {
      if (isset($base_field_definitions[$field_name]) && in_array($key, array('id', 'revision', 'uuid', 'bundle')) && $base_field_definitions[$field_name]->isRevisionable()) {
        throw new \LogicException(String::format('The @field field cannot be revisionable as it is used as @key entity key.', array('@field' => $base_field_definitions[$field_name]->getLabel(), '@key' => $key)));
      }
      if (isset($base_field_definitions[$field_name]) && in_array($key, array('id', 'revision', 'uuid', 'bundle', 'langcode')) && $base_field_definitions[$field_name]->isTranslatable()) {
        throw new \LogicException(String::format('The @field field cannot be translatable as it is used as @key entity key.', array('@field' => $base_field_definitions[$field_name]->getLabel(), '@key' => $key)));
444 445
      }
    }
446 447 448 449 450 451 452 453 454 455
    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.
456
      $cid = 'entity_bundle_field_definitions:' . $entity_type_id . ':' . $bundle . ':' . $this->languageManager->getCurrentLanguage()->getId();
457
      if ($cache = $this->cacheBackend->get($cid)) {
458 459 460 461
        $bundle_field_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
462
        $bundle_field_definitions = $this->buildBundleFieldDefinitions($entity_type_id, $bundle, $base_field_definitions);
463
        $this->cacheBackend->set($cid, $bundle_field_definitions, Cache::PERMANENT, array('entity_types', 'entity_field_info'));
464 465 466 467 468 469
      }
      // 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);
470
    }
471 472 473 474 475 476 477 478
    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
479
   *   \Drupal\Core\Entity\FieldableEntityInterface are supported.
480 481 482 483 484 485 486 487 488
   * @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.
   */
489
  protected function buildBundleFieldDefinitions($entity_type_id, $bundle, array $base_field_definitions) {
490 491 492
    $entity_type = $this->getDefinition($entity_type_id);
    $class = $entity_type->getClass();

493 494
    // Allow the entity class to provide bundle fields and bundle-specific
    // overrides of base fields.
495
    $bundle_field_definitions = $class::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions);
496 497 498 499 500 501 502 503 504 505 506 507 508

    // 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;
    }

509 510
    $provider = $entity_type->getProvider();
    foreach ($bundle_field_definitions as $definition) {
511 512
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
513
      if ($definition instanceof BaseFieldDefinition) {
514 515 516
        $definition->setProvider($provider);
      }
    }
517

518 519 520 521 522 523 524
    // 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) {
525 526
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
527
          if ($definition instanceof BaseFieldDefinition) {
528 529 530 531 532 533
            $definition->setProvider($module);
          }
          $bundle_field_definitions[$field_name] = $definition;
        }
      }
    }
534

535 536
    // Automatically set the field name, target entity type and bundle
    // for non-configurable fields.
537
    foreach ($bundle_field_definitions as $field_name => $field_definition) {
538
      if ($field_definition instanceof BaseFieldDefinition) {
539 540
        $field_definition->setName($field_name);
        $field_definition->setTargetEntityTypeId($entity_type_id);
541
        $field_definition->setTargetBundle($bundle);
542 543
      }
    }
544 545 546 547 548

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

    return $bundle_field_definitions;
549 550
  }

551 552 553 554 555 556 557 558 559 560 561 562 563
  /**
   * {@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.
564
      $cid = 'entity_field_storage_definitions:' . $entity_type_id . ':' . $this->languageManager->getCurrentLanguage()->getId();
565
      if ($cache = $this->cacheBackend->get($cid)) {
566 567 568 569 570
        $field_storage_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
        $field_storage_definitions = $this->buildFieldStorageDefinitions($entity_type_id);
571
        $this->cacheBackend->set($cid, $field_storage_definitions, Cache::PERMANENT, array('entity_types', 'entity_field_info'));
572 573 574 575 576 577
      }
      $this->fieldStorageDefinitions[$entity_type_id] += $field_storage_definitions;
    }
    return $this->fieldStorageDefinitions[$entity_type_id];
  }

578 579 580 581 582 583 584
  /**
   * {@inheritdoc}
   */
  public function getFieldMap() {
    if (!$this->fieldMap) {
      // Not prepared, try to load from cache.
      $cid = 'entity_field_map';
585
      if ($cache = $this->cacheBackend->get($cid)) {
586 587 588 589 590
        $this->fieldMap = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
        foreach ($this->getDefinitions() as $entity_type_id => $entity_type) {
591
          if ($entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
592 593 594 595 596 597 598 599 600
            foreach ($this->getBundleInfo($entity_type_id) as $bundle => $bundle_info) {
              foreach ($this->getFieldDefinitions($entity_type_id, $bundle) as $field_name => $field_definition) {
                $this->fieldMap[$entity_type_id][$field_name]['type'] = $field_definition->getType();
                $this->fieldMap[$entity_type_id][$field_name]['bundles'][] = $bundle;
              }
            }
          }
        }

601
        $this->cacheBackend->set($cid, $this->fieldMap, Cache::PERMANENT, array('entity_types', 'entity_field_info'));
602 603 604 605 606
      }
    }
    return $this->fieldMap;
  }

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
  /**
   * {@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];
  }

626 627 628 629 630
  /**
   * Builds field storage definitions for an entity type.
   *
   * @param string $entity_type_id
   *   The entity type ID. Only entity types that implement
631
   *   \Drupal\Core\Entity\FieldableEntityInterface are supported
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
   *
   * @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.
649
          if ($definition instanceof BaseFieldDefinition) {
650 651 652 653 654 655 656 657 658 659 660 661 662
            $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;
  }

663
  /**
664
   * {@inheritdoc}
665 666
   */
  public function clearCachedFieldDefinitions() {
667 668
    $this->baseFieldDefinitions = array();
    $this->fieldDefinitions = array();
669
    $this->fieldStorageDefinitions = array();
670
    $this->fieldMap = array();
671
    $this->fieldMapByFieldType = array();
672 673
    $this->displayModeInfo = array();
    $this->extraFields = array();
674
    Cache::deleteTags(array('entity_field_info'));
675 676 677 678 679 680 681 682 683 684
    // 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();
685
    Cache::deleteTags(array('entity_bundles'));
686 687
    // Entity bundles are exposed as data types, clear that cache too.
    $this->typedDataManager->clearCachedDefinitions();
688 689
  }

690
  /**
691
   * {@inheritdoc}
692 693 694 695 696 697 698
   */
  public function getBundleInfo($entity_type) {
    $bundle_info = $this->getAllBundleInfo();
    return isset($bundle_info[$entity_type]) ? $bundle_info[$entity_type] : array();
  }

  /**
699
   * {@inheritdoc}
700 701
   */
  public function getAllBundleInfo() {
702
    if (empty($this->bundleInfo)) {
703
      $langcode = $this->languageManager->getCurrentLanguage()->getId();
704
      if ($cache = $this->cacheBackend->get("entity_bundle_info:$langcode")) {
705 706 707 708
        $this->bundleInfo = $cache->data;
      }
      else {
        $this->bundleInfo = $this->moduleHandler->invokeAll('entity_bundle_info');
709 710
        // First look for entity types that act as bundles for others, load them
        // and add them as bundles.
711
        foreach ($this->getDefinitions() as $type => $entity_type) {
712 713 714 715 716 717 718 719
          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.
720
          if (!isset($this->bundleInfo[$type])) {
721
            $this->bundleInfo[$type][$type]['label'] = $entity_type->getLabel();
722 723 724
          }
        }
        $this->moduleHandler->alter('entity_bundle_info', $this->bundleInfo);
725
        $this->cacheBackend->set("entity_bundle_info:$langcode", $this->bundleInfo, Cache::PERMANENT, array('entity_types', 'entity_bundles'));
726 727 728 729 730 731
      }
    }

    return $this->bundleInfo;
  }

732 733 734 735 736 737 738 739 740 741 742 743
  /**
   * {@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.
744
    $cache_id = 'entity_bundle_extra_fields:' . $entity_type_id . ':' . $bundle . ':' . $this->languageManager->getCurrentLanguage()->getId();
745
    $cached = $this->cacheBackend->get($cache_id);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
    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;
761
    $this->cacheBackend->set($cache_id, $info, Cache::PERMANENT, array(
762
      'entity_field_info',
763 764 765 766 767
    ));

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

768
  /**
769
   * {@inheritdoc}
770
   */
771
  public function getEntityTypeLabels($group = FALSE) {
772
    $options = array();
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    $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;
793 794 795 796 797
    }

    return $options;
  }

798 799 800 801 802 803 804 805
  /**
   * {@inheritdoc}
   */
  public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
    $translation = $entity;

    if ($entity instanceof TranslatableInterface) {
      if (empty($langcode)) {
806
        $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
807 808 809 810 811
      }

      // Retrieve language fallback candidates to perform the entity language
      // negotiation.
      $context['data'] = $entity;
812 813
      $context += array('operation' => 'entity_view', 'langcode' => $langcode);
      $candidates = $this->languageManager->getFallbackCandidates($context);
814 815 816

      // Ensure the default language has the proper language code.
      $default_language = $entity->getUntranslated()->language();
817
      $candidates[$default_language->getId()] = LanguageInterface::LANGCODE_DEFAULT;
818 819 820 821 822 823 824 825 826 827 828 829 830

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

    return $translation;
  }

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
  /**
   * {@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);
  }

  /**
   * Returns the entity display mode info for all entity types.
   *
   * @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';
871
      $entity_type_id = 'entity_' . $display_type;
872
      $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_INTERFACE)->getId();
873
      if ($cache = $this->cacheBackend->get("$key:$langcode")) {
874 875 876 877
        $this->displayModeInfo[$display_type] = $cache->data;
      }
      else {
        $this->displayModeInfo[$display_type] = array();
878
        foreach ($this->getStorage($entity_type_id)->loadMultiple() as $display_mode) {
879
          list($display_mode_entity_type, $display_mode_name) = explode('.', $display_mode->id(), 2);
880
          $this->displayModeInfo[$display_type][$display_mode_entity_type][$display_mode_name] = $display_mode->toArray();
881 882
        }
        $this->moduleHandler->alter($key, $this->displayModeInfo[$display_type]);
883
        $this->cacheBackend->set("$key:$langcode", $this->displayModeInfo[$display_type], CacheBackendInterface::CACHE_PERMANENT, array('entity_types', 'entity_field_info'));
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
      }
    }

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

  /**
   * Returns the entity display mode info for a specific entity type.
   *
   * @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);
  }

  /**
   * Returns an array of display mode options.
   *
   * @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;
  }

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
  /**
   * {@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);
  }

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
  /**
   * {@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);
  }

996 997 998 999
  /**
   * {@inheritdoc}
   */
  public function onEntityTypeCreate(EntityTypeInterface $entity_type) {
1000 1001
    $entity_type_id = $entity_type->id();

1002 1003
    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
1004
    $storage = $this->getStorage($entity_type_id);
1005 1006 1007
    if ($storage instanceof EntityTypeListenerInterface) {
      $storage->onEntityTypeCreate($entity_type);
    }
1008

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

1011
    $this->setLastInstalledDefinition($entity_type);
1012
    if ($entity_type->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
1013 1014
      $this->setLastInstalledFieldStorageDefinitions($entity_type_id, $this->getFieldStorageDefinitions($entity_type_id));
    }
1015 1016 1017 1018 1019 1020
  }

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

1023 1024
    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
1025
    $storage = $this->getStorage($entity_type_id);
1026 1027 1028
    if ($storage instanceof EntityTypeListenerInterface) {
      $storage->onEntityTypeUpdate($entity_type, $original);
    }
1029

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

1032
    $this->setLastInstalledDefinition($entity_type);
1033 1034 1035 1036 1037 1038
  }

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

1041 1042
    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
1043
    $storage = $this->getStorage($entity_type_id);
1044 1045 1046
    if ($storage instanceof EntityTypeListenerInterface) {
      $storage->onEntityTypeDelete($entity_type);
    }
1047

1048 1049
    $this->eventDispatcher->dispatch(EntityTypeEvents::DELETE, new EntityTypeEvent($entity_type));

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    $this->deleteLastInstalledDefinition($entity_type_id);
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) {
    $entity_type_id = $storage_definition->getTargetEntityTypeId();

    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
    $storage = $this->getStorage($entity_type_id);
    if ($storage instanceof FieldStorageDefinitionListenerInterface) {
      $storage->onFieldStorageDefinitionCreate($storage_definition);
    }

1066 1067
    $this->eventDispatcher->dispatch(FieldStorageDefinitionEvents::CREATE, new FieldStorageDefinitionEvent($storage_definition));

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    $this->setLastInstalledFieldStorageDefinition($storage_definition);
    $this->clearCachedFieldDefinitions();
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
    $entity_type_id = $storage_definition->getTargetEntityTypeId();

    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
    $storage = $this->getStorage($entity_type_id);
    if ($storage instanceof FieldStorageDefinitionListenerInterface) {
      $storage->onFieldStorageDefinitionUpdate($storage_definition, $original);
    }

1085 1086
    $this->eventDispatcher->dispatch(FieldStorageDefinitionEvents::UPDATE, new FieldStorageDefinitionEvent($storage_definition, $original));

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    $this->setLastInstalledFieldStorageDefinition($storage_definition);
    $this->clearCachedFieldDefinitions();
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) {
    $entity_type_id = $storage_definition->getTargetEntityTypeId();

    // @todo Forward this to all interested handlers, not only storage, once
    //   iterating handlers is possible: https://www.drupal.org/node/2332857.
    $storage = $this->getStorage($entity_type_id);
    if ($storage instanceof FieldStorageDefinitionListenerInterface) {
      $storage->onFieldStorageDefinitionDelete($storage_definition);
    }

1104 1105
    $this->eventDispatcher->dispatch(FieldStorageDefinitionEvents::DELETE, new FieldStorageDefinitionEvent($storage_definition));

1106 1107
    $this->deleteLastInstalledFieldStorageDefinition($storage_definition);
    $this->clearCachedFieldDefinitions();
1108 1109
  }

1110
  /**
1111 1112
   * {@inheritdoc}
   */
1113
  public function onBundleCreate($bundle, $entity_type_id) {
1114 1115 1116
    $this->clearCachedBundles();
    // Notify the entity storage.
    $storage = $this->getStorage($entity_type_id);
1117 1118
    if ($storage instanceof EntityBundleListenerInterface) {
      $storage->onBundleCreate($bundle, $entity_type_id);
1119 1120 1121 1122 1123 1124 1125
    }
    // Invoke hook_entity_bundle_create() hook.
    $this->moduleHandler->invokeAll('entity_bundle_create', array($entity_type_id, $bundle));
  }

  /**
   * {@inheritdoc}
1126
   */
1127
  public function onBundleRename($bundle_old, $bundle_new, $entity_type_id) {
1128 1129 1130
    $this->clearCachedBundles();
    // Notify the entity storage.
    $storage = $this->getStorage($entity_type_id);
1131 1132
    if ($storage instanceof EntityBundleListenerInterface) {
      $storage->onBundleRename($bundle_old, $bundle_new, $entity_type_id);
1133 1134
    }

1135 1136 1137 1138 1139 1140 1141 1142
    // Rename existing base field bundle overrides.
    $overrides = $this->getStorage('base_field_override')->loadByProperties(array('entity_type' => $entity_type_id, 'bundle' => $bundle_old));
    foreach ($overrides as $override) {
      $override->set('id', $entity_type_id . '.' . $bundle_new . '.' . $override->field_name);
      $override->bundle = $bundle_new;
      $override->allowBundleRename();
      $override->save();
    }
1143 1144 1145 1146 1147 1148 1149 1150 1151

    // Invoke hook_entity_bundle_rename() hook.
    $this->moduleHandler->invokeAll('entity_bundle_rename', array($entity_type_id, $bundle_old, $bundle_new));
    $this->clearCachedFieldDefinitions();
  }

  /**
   * {@inheritdoc}
   */
1152
  public function onBundleDelete($bundle, $entity_type_id) {
1153 1154 1155
    $this->clearCachedBundles();
    // Notify the entity storage.
    $storage = $this->getStorage($entity_type_id);
1156 1157
    if ($storage instanceof EntityBundleListenerInterface) {
      $storage->onBundleDelete($bundle, $entity_type_id);
1158 1159 1160 1161
    }
    // Invoke hook_entity_bundle_delete() hook.
    $this->moduleHandler->invokeAll('entity_bundle_delete', array($entity_type_id, $bundle));
    $this->clearCachedFieldDefinitions();
1162 1163
  }

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  /**
   * {@inheritdoc}
   */
  public function getLastInstalledDefinition($entity_type_id) {
    return $this->installedDefinitions->get($entity_type_id . '.entity_type');
  }

  /**
   * Stores the entity type definition in the application state.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   */
  protected function setLastInstalledDefinition(EntityTypeInterface $entity_type) {
    $entity_type_id = $entity_type->id();
    $this->installedDefinitions->set($entity_type_id . '.entity_type', $entity_type);
  }

  /**
   * Deletes the entity type definition from the application state.
   *
   * @param string $entity_type_id
   *   The entity type definition identifier.
   */
  protected function deleteLastInstalledDefinition($entity_type_id) {
    $this->installedDefinitions->delete($entity_type_id . '.entity_type');
    // Clean up field storage definitions as well. Even if the entity type
    // isn't currently fieldable, there might be legacy definitions or an
    // empty array stored from when it was.
    $this->installedDefinitions->delete($entity_type_id . '.field_storage_definitions');
  }

  /**
   * {@inheritdoc}
   */
  public function getLastInstalledFieldStorageDefinitions($entity_type_id) {
1200
    return $this->installedDefinitions->get($entity_type_id . '.field_storage_definitions', array());
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
  }

  /**
   * Stores the entity type's field storage definitions in the application state.
   *
   * @param string $entity_type_id
   *   The entity type identifier.
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface[] $storage_definitions
   *   An array of field storage definitions.
   */
  protected function setLastInstalledFieldStorageDefinitions($entity_type_id, array $storage_definitions) {
    $this->installedDefinitions->set($entity_type_id . '.field_storage_definitions', $storage_definitions);
  }

  /**
   * Stores the field storage definition in the application state.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition
   *   The field storage definition.
   */
  protected function setLastInstalledFieldStorageDefinition(FieldStorageDefinitionInterface $storage_definition) {
    $entity_type_id = $storage_definition->getTargetEntityTypeId();
    $definitions = $this->getLastInstalledFieldStorageDefinitions($entity_type_id);
    $definitions[$storage_definition->getName()] = $storage_definition;
    $this->setLastInstalledFieldStorageDefinitions($entity_type_id, $definitions);
  }

  /**
   * Deletes the field storage definition from the application state.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition
   *   The field storage definition.
   */
  protected function deleteLastInstalledFieldStorageDefinition(FieldStorageDefinitionInterface $storage_definition) {
    $entity_type_id = $storage_definition->getTargetEntityTypeId();
    $definitions = $this->getLastInstalledFieldStorageDefinitions($entity_type_id);
    unset($definitions[$storage_definition->getName()]);
    $this->setLastInstalledFieldStorageDefinitions($entity_type_id, $definitions);
  }

1241
}