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

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

  use ContainerAwareTrait;
47
  use StringTranslationTrait;
48

49 50 51 52 53 54 55
  /**
   * Extra fields by bundle.
   *
   * @var array
   */
  protected $extraFields = array();

56
  /**
57
   * Contains instantiated handlers keyed by handler type and entity type.
58 59 60
   *
   * @var array
   */
61
  protected $handlers = array();
62

63
  /**
64
   * Static cache of base field definitions.
65 66 67
   *
   * @var array
   */
68
  protected $baseFieldDefinitions;
69 70 71 72 73 74 75 76

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

77 78 79 80
  /**
   * Static cache of field storage definitions per entity type.
   *
   * Elements of the array:
81
   *  - $entity_type_id: \Drupal\Core\Field\BaseFieldDefinition[]
82 83 84 85 86
   *
   * @var array
   */
  protected $fieldStorageDefinitions;

87 88 89 90 91 92 93
  /**
   * The string translationManager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

94 95 96 97 98 99 100
  /**
   * The class resolver.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

101 102 103 104 105 106 107
  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManager
   */
  protected $typedDataManager;

108 109 110 111 112 113 114
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

115
  /**
116 117 118 119 120 121
   * Static cache of bundle information.
   *
   * @var array
   */
  protected $bundleInfo;

122 123 124 125 126 127 128
  /**
   * Static cache of display modes information.
   *
   * @var array
   */
  protected $displayModeInfo = array();

129 130 131 132 133 134 135 136 137 138
  /**
   * 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();

139 140 141 142 143 144 145 146 147 148
  /**
   * 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();

149 150 151 152 153 154 155
  /**
   * Contains cached mappings of class names to entity types.
   *
   * @var array
   */
  protected $classNameEntityTypeMap = array();

156 157
  /**
   * Constructs a new Entity plugin manager.
158
   *
159 160 161
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
162 163 164 165
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend to use.
166
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
167
   *   The language manager.
168 169
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
   *   The string translationManager.
170 171
   * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
   *   The class resolver.
172
   */
173
  public function __construct(\Traversable $namespaces, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, TranslationInterface $translation_manager, ClassResolverInterface $class_resolver, TypedDataManager $typed_data_manager) {
174
    parent::__construct('Entity', $namespaces, $module_handler, 'Drupal\Core\Entity\Annotation\EntityType');
175

176
    $this->setCacheBackend($cache, 'entity_type', array('entity_types' => TRUE));
177
    $this->alterInfo('entity_type');
178

179
    $this->languageManager = $language_manager;
180
    $this->translationManager = $translation_manager;
181
    $this->classResolver = $class_resolver;
182
    $this->typedDataManager = $typed_data_manager;
183 184
  }

185 186 187 188 189
  /**
   * {@inheritdoc}
   */
  public function clearCachedDefinitions() {
    parent::clearCachedDefinitions();
190 191
    $this->clearCachedBundles();
    $this->clearCachedFieldDefinitions();
192
    $this->classNameEntityTypeMap = array();
193 194
  }

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  /**
   * {@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;
  }

216
  /**
217
   * {@inheritdoc}
218
   */
219 220
  public function getDefinition($entity_type_id, $exception_on_invalid = TRUE) {
    if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
221
      return $entity_type;
222
    }
223 224 225 226
    elseif (!$exception_on_invalid) {
      return NULL;
    }

227
    throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));
228 229
  }

230
  /**
231
   * {@inheritdoc}
232
   */
233
  public function hasHandler($entity_type, $handler_type) {
234
    if ($definition = $this->getDefinition($entity_type, FALSE)) {
235
      return $definition->hasHandlerClass($handler_type);
236
    }
237
    return FALSE;
238 239 240
  }

  /**
241
   * {@inheritdoc}
242
   */
243
  public function getStorage($entity_type) {
244
    return $this->getHandler($entity_type, 'storage');
245 246 247
  }

  /**
248
   * {@inheritdoc}
249
   */
250
  public function getListBuilder($entity_type) {
251
    return $this->getHandler($entity_type, 'list_builder');
252 253 254
  }

  /**
255
   * {@inheritdoc}
256
   */
257
  public function getFormObject($entity_type, $operation) {
258
    if (!isset($this->handlers['form'][$operation][$entity_type])) {
259 260 261
      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));
      }
262

263
      $form_object = $this->classResolver->getInstanceFromDefinition($class);
264

265
      $form_object
266
        ->setStringTranslation($this->translationManager)
267 268
        ->setModuleHandler($this->moduleHandler)
        ->setOperation($operation);
269
      $this->handlers['form'][$operation][$entity_type] = $form_object;
270
    }
271
    return $this->handlers['form'][$operation][$entity_type];
272 273 274
  }

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

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

  /**
289
   * {@inheritdoc}
290
   */
291 292
  public function getHandler($entity_type, $handler_type) {
    if (!isset($this->handlers[$handler_type][$entity_type])) {
293
      $definition = $this->getDefinition($entity_type);
294
      $class = $definition->getHandlerClass($handler_type);
295
      if (!$class) {
296
        throw new InvalidPluginDefinitionException($entity_type, sprintf('The "%s" entity type did not specify a %s handler.', $entity_type, $handler_type));
297
      }
298 299
      if (is_subclass_of($class, 'Drupal\Core\Entity\EntityHandlerInterface')) {
        $handler = $class::createInstance($this->container, $definition);
300 301
      }
      else {
302
        $handler = new $class($definition);
303
      }
304 305
      if (method_exists($handler, 'setModuleHandler')) {
        $handler->setModuleHandler($this->moduleHandler);
306
      }
307 308
      if (method_exists($handler, 'setStringTranslation')) {
        $handler->setStringTranslation($this->translationManager);
309
      }
310
      $this->handlers[$handler_type][$entity_type] = $handler;
311
    }
312
    return $this->handlers[$handler_type][$entity_type];
313 314
  }

315
  /**
316
   * {@inheritdoc}
317
   */
318 319 320 321 322
  public function getBaseFieldDefinitions($entity_type_id) {
    // Check the static cache.
    if (!isset($this->baseFieldDefinitions[$entity_type_id])) {
      // Not prepared, try to load from cache.
      $cid = 'entity_base_field_definitions:' . $entity_type_id . ':' . $this->languageManager->getCurrentLanguage()->id;
323
      if ($cache = $this->cacheBackend->get($cid)) {
324
        $this->baseFieldDefinitions[$entity_type_id] = $cache->data;
325 326
      }
      else {
327 328
        // Rebuild the definitions and put it into the cache.
        $this->baseFieldDefinitions[$entity_type_id] = $this->buildBaseFieldDefinitions($entity_type_id);
329
        $this->cacheBackend->set($cid, $this->baseFieldDefinitions[$entity_type_id], Cache::PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
330 331 332 333 334 335 336 337 338 339
       }
     }
    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
340
   *   \Drupal\Core\Entity\ContentEntityInterface are supported.
341 342 343 344 345
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   An array of field definitions, keyed by field name.
   *
   * @throws \LogicException
346 347
   *   Thrown if a config entity type is given or if one of the entity keys is
   *   flagged as translatable.
348 349 350 351 352
   */
  protected function buildBaseFieldDefinitions($entity_type_id) {
    $entity_type = $this->getDefinition($entity_type_id);
    $class = $entity_type->getClass();

353 354 355 356 357
    // Fail with an exception for config entity types.
    if (!$entity_type->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface')) {
      throw new \LogicException(String::format('Getting the base fields is not supported for entity type @type.', array('@type' => $entity_type->getLabel())));
    }

358
    // Retrieve base field definitions and assign them the entity type provider.
359
    $base_field_definitions = $class::baseFieldDefinitions($entity_type);
360 361
    $provider = $entity_type->getProvider();
    foreach ($base_field_definitions as $definition) {
362 363
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
364
      if ($definition instanceof BaseFieldDefinition) {
365 366 367
        $definition->setProvider($provider);
      }
    }
368

369 370 371 372 373 374 375
    // 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) {
376 377
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
378
          if ($definition instanceof BaseFieldDefinition && $definition->getProvider() == NULL) {
379 380 381 382 383 384
            $definition->setProvider($module);
          }
          $base_field_definitions[$field_name] = $definition;
        }
      }
    }
385

386 387
    // Automatically set the field name, target entity type and bundle
    // for non-configurable fields.
388
    foreach ($base_field_definitions as $field_name => $base_field_definition) {
389
      if ($base_field_definition instanceof BaseFieldDefinition) {
390 391
        $base_field_definition->setName($field_name);
        $base_field_definition->setTargetEntityTypeId($entity_type_id);
392
        $base_field_definition->setBundle(NULL);
393 394 395 396 397 398
      }
    }

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

399 400 401 402 403 404 405 406 407
    // 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)));
408 409
      }
    }
410 411 412 413 414 415 416 417 418 419 420
    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.
      $cid = 'entity_bundle_field_definitions:' . $entity_type_id . ':' . $bundle . ':' . $this->languageManager->getCurrentLanguage()->id;
421
      if ($cache = $this->cacheBackend->get($cid)) {
422 423 424 425
        $bundle_field_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
426
        $bundle_field_definitions = $this->buildBundleFieldDefinitions($entity_type_id, $bundle, $base_field_definitions);
427
        $this->cacheBackend->set($cid, $bundle_field_definitions, Cache::PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
428 429 430 431 432 433
      }
      // 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);
434
    }
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    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
   *   \Drupal\Core\Entity\ContentEntityInterface are supported.
   * @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.
   */
453
  protected function buildBundleFieldDefinitions($entity_type_id, $bundle, array $base_field_definitions) {
454 455 456
    $entity_type = $this->getDefinition($entity_type_id);
    $class = $entity_type->getClass();

457 458
    // Allow the entity class to provide bundle fields and bundle-specific
    // overrides of base fields.
459
    $bundle_field_definitions = $class::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions);
460 461 462 463 464 465 466 467 468 469 470 471 472

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

473 474
    $provider = $entity_type->getProvider();
    foreach ($bundle_field_definitions as $definition) {
475 476
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
477
      if ($definition instanceof BaseFieldDefinition) {
478 479 480
        $definition->setProvider($provider);
      }
    }
481

482 483 484 485 486 487 488
    // 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) {
489 490
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
491
          if ($definition instanceof BaseFieldDefinition) {
492 493 494 495 496 497
            $definition->setProvider($module);
          }
          $bundle_field_definitions[$field_name] = $definition;
        }
      }
    }
498

499 500
    // Automatically set the field name, target entity type and bundle
    // for non-configurable fields.
501
    foreach ($bundle_field_definitions as $field_name => $field_definition) {
502
      if ($field_definition instanceof BaseFieldDefinition) {
503 504
        $field_definition->setName($field_name);
        $field_definition->setTargetEntityTypeId($entity_type_id);
505
        $field_definition->setBundle($bundle);
506 507
      }
    }
508 509 510 511 512

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

    return $bundle_field_definitions;
513 514
  }

515 516 517 518 519 520 521 522 523 524 525 526 527 528
  /**
   * {@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.
      $cid = 'entity_field_storage_definitions:' . $entity_type_id . ':' . $this->languageManager->getCurrentLanguage()->id;
529
      if ($cache = $this->cacheBackend->get($cid)) {
530 531 532 533 534
        $field_storage_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
        $field_storage_definitions = $this->buildFieldStorageDefinitions($entity_type_id);
535
        $this->cacheBackend->set($cid, $field_storage_definitions, Cache::PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
536 537 538 539 540 541
      }
      $this->fieldStorageDefinitions[$entity_type_id] += $field_storage_definitions;
    }
    return $this->fieldStorageDefinitions[$entity_type_id];
  }

542 543 544 545 546 547 548
  /**
   * {@inheritdoc}
   */
  public function getFieldMap() {
    if (!$this->fieldMap) {
      // Not prepared, try to load from cache.
      $cid = 'entity_field_map';
549
      if ($cache = $this->cacheBackend->get($cid)) {
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        $this->fieldMap = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
        foreach ($this->getDefinitions() as $entity_type_id => $entity_type) {
          if ($entity_type->isSubclassOf('\Drupal\Core\Entity\ContentEntityInterface')) {
            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;
              }
            }
          }
        }

565
        $this->cacheBackend->set($cid, $this->fieldMap, Cache::PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
566 567 568 569 570
      }
    }
    return $this->fieldMap;
  }

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
  /**
   * {@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];
  }

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
  /**
   * Builds field storage definitions for an entity type.
   *
   * @param string $entity_type_id
   *   The entity type ID. Only entity types that implement
   *   \Drupal\Core\Entity\ContentEntityInterface are supported
   *
   * @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.
613
          if ($definition instanceof BaseFieldDefinition) {
614 615 616 617 618 619 620 621 622 623 624 625 626
            $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;
  }

627
  /**
628
   * {@inheritdoc}
629 630
   */
  public function clearCachedFieldDefinitions() {
631 632
    $this->baseFieldDefinitions = array();
    $this->fieldDefinitions = array();
633
    $this->fieldStorageDefinitions = array();
634
    $this->fieldMap = array();
635
    $this->fieldMapByFieldType = array();
636 637
    $this->displayModeInfo = array();
    $this->extraFields = array();
638
    Cache::deleteTags(array('entity_field_info' => TRUE));
639 640 641 642 643 644 645 646 647 648 649 650 651
    // 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();
    Cache::deleteTags(array('entity_bundles' => TRUE));
    // Entity bundles are exposed as data types, clear that cache too.
    $this->typedDataManager->clearCachedDefinitions();
652 653
  }

654
  /**
655
   * {@inheritdoc}
656 657 658 659 660 661 662
   */
  public function getBundleInfo($entity_type) {
    $bundle_info = $this->getAllBundleInfo();
    return isset($bundle_info[$entity_type]) ? $bundle_info[$entity_type] : array();
  }

  /**
663
   * {@inheritdoc}
664 665
   */
  public function getAllBundleInfo() {
666
    if (empty($this->bundleInfo)) {
667
      $langcode = $this->languageManager->getCurrentLanguage()->id;
668
      if ($cache = $this->cacheBackend->get("entity_bundle_info:$langcode")) {
669 670 671 672
        $this->bundleInfo = $cache->data;
      }
      else {
        $this->bundleInfo = $this->moduleHandler->invokeAll('entity_bundle_info');
673 674
        // First look for entity types that act as bundles for others, load them
        // and add them as bundles.
675
        foreach ($this->getDefinitions() as $type => $entity_type) {
676 677 678 679 680 681 682 683
          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.
684
          if (!isset($this->bundleInfo[$type])) {
685
            $this->bundleInfo[$type][$type]['label'] = $entity_type->getLabel();
686 687 688
          }
        }
        $this->moduleHandler->alter('entity_bundle_info', $this->bundleInfo);
689
        $this->cacheBackend->set("entity_bundle_info:$langcode", $this->bundleInfo, Cache::PERMANENT, array('entity_types' => TRUE, 'entity_bundles' => TRUE));
690 691 692 693 694 695
      }
    }

    return $this->bundleInfo;
  }

696 697 698 699 700 701 702 703 704 705 706 707 708
  /**
   * {@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.
    $cache_id = 'entity_bundle_extra_fields:' . $entity_type_id . ':' . $bundle . ':' . $this->languageManager->getCurrentLanguage()->id;
709
    $cached = $this->cacheBackend->get($cache_id);
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
    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;
725
    $this->cacheBackend->set($cache_id, $info, Cache::PERMANENT, array(
726 727 728 729 730 731
      'entity_field_info' => TRUE,
    ));

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

732
  /**
733
   * {@inheritdoc}
734
   */
735
  public function getEntityTypeLabels($group = FALSE) {
736
    $options = array();
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    $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;
757 758 759 760 761
    }

    return $options;
  }

762 763 764 765 766 767 768 769
  /**
   * {@inheritdoc}
   */
  public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
    $translation = $entity;

    if ($entity instanceof TranslatableInterface) {
      if (empty($langcode)) {
770
        $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->id;
771 772 773 774 775
      }

      // Retrieve language fallback candidates to perform the entity language
      // negotiation.
      $context['data'] = $entity;
776 777
      $context += array('operation' => 'entity_view', 'langcode' => $langcode);
      $candidates = $this->languageManager->getFallbackCandidates($context);
778 779 780

      // Ensure the default language has the proper language code.
      $default_language = $entity->getUntranslated()->language();
781
      $candidates[$default_language->id] = LanguageInterface::LANGCODE_DEFAULT;
782 783 784 785 786 787 788 789 790 791 792 793 794

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

    return $translation;
  }

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
  /**
   * {@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';
835
      $entity_type_id = 'entity_' . $display_type;
836
      $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_INTERFACE)->id;
837
      if ($cache = $this->cacheBackend->get("$key:$langcode")) {
838 839 840 841
        $this->displayModeInfo[$display_type] = $cache->data;
      }
      else {
        $this->displayModeInfo[$display_type] = array();
842
        foreach ($this->getStorage($entity_type_id)->loadMultiple() as $display_mode) {
843
          list($display_mode_entity_type, $display_mode_name) = explode('.', $display_mode->id(), 2);
844
          $this->displayModeInfo[$display_type][$display_mode_entity_type][$display_mode_name] = $display_mode->toArray();
845 846
        }
        $this->moduleHandler->alter($key, $this->displayModeInfo[$display_type]);
847
        $this->cacheBackend->set("$key:$langcode", $this->displayModeInfo[$display_type], CacheBackendInterface::CACHE_PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 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
      }
    }

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

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
  /**
   * {@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);
  }

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
  /**
   * {@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);
  }

960 961 962 963 964 965 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 onEntityTypeCreate(EntityTypeInterface $entity_type) {
    // @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 EntityTypeListenerInterface) {
      $storage->onEntityTypeCreate($entity_type);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function onEntityTypeUpdate(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
    // @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 EntityTypeListenerInterface) {
      $storage->onEntityTypeUpdate($entity_type, $original);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function onEntityTypeDelete(EntityTypeInterface $entity_type) {
    // @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 EntityTypeListenerInterface) {
      $storage->onEntityTypeDelete($entity_type);
    }
  }

996
  /**
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
   * {@inheritdoc}
   */
  public function onBundleCreate($entity_type_id, $bundle) {
    $this->clearCachedBundles();
    // Notify the entity storage.
    $storage = $this->getStorage($entity_type_id);
    if ($storage instanceof FieldableEntityStorageInterface) {
      $storage->onBundleCreate($bundle);
    }
    // Invoke hook_entity_bundle_create() hook.
    $this->moduleHandler->invokeAll('entity_bundle_create', array($entity_type_id, $bundle));
  }

  /**
   * {@inheritdoc}
1012 1013
   */
  public function onBundleRename($entity_type_id, $bundle_old, $bundle_new) {
1014 1015 1016 1017 1018 1019 1020
    $this->clearCachedBundles();
    // Notify the entity storage.
    $storage = $this->getStorage($entity_type_id);
    if ($storage instanceof FieldableEntityStorageInterface) {
      $storage->onBundleRename($bundle_old, $bundle_new);
    }

1021 1022 1023 1024 1025 1026 1027 1028
    // 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();
    }
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

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

  /**
   * {@inheritdoc}
   */
  public function onBundleDelete($entity_type_id, $bundle) {
    $this->clearCachedBundles();
    // Notify the entity storage.
    $storage = $this->getStorage($entity_type_id);
    if ($storage instanceof FieldableEntityStorageInterface) {
      $storage->onBundleDelete($bundle);
    }
    // Invoke hook_entity_bundle_delete() hook.
    $this->moduleHandler->invokeAll('entity_bundle_delete', array($entity_type_id, $bundle));
    $this->clearCachedFieldDefinitions();
1048 1049
  }

1050
}