EntityManager.php 31.3 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\FieldDefinition;
15
use Drupal\Core\Cache\Cache;
16
use Drupal\Core\Cache\CacheBackendInterface;
17
use Drupal\Core\Extension\ModuleHandlerInterface;
18
use Drupal\Core\Language\LanguageManagerInterface;
19
use Drupal\Core\Language\Language;
20
use Drupal\Core\Plugin\DefaultPluginManager;
21
use Drupal\Core\StringTranslation\StringTranslationTrait;
22
use Drupal\Core\StringTranslation\TranslationInterface;
23
use Drupal\Core\TypedData\TranslatableInterface;
24 25
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
26 27 28 29

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

  use ContainerAwareTrait;
44
  use StringTranslationTrait;
45

46 47 48 49 50 51 52
  /**
   * Extra fields by bundle.
   *
   * @var array
   */
  protected $extraFields = array();

53 54 55 56 57 58 59
  /**
   * Contains instantiated controllers keyed by controller type and entity type.
   *
   * @var array
   */
  protected $controllers = array();

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

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

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

84 85 86 87 88 89 90
  /**
   * The string translationManager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

91 92 93 94 95 96 97
  /**
   * The class resolver.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

98
  /**
99 100 101 102 103 104
   * Static cache of bundle information.
   *
   * @var array
   */
  protected $bundleInfo;

105 106 107 108 109 110 111
  /**
   * Static cache of display modes information.
   *
   * @var array
   */
  protected $displayModeInfo = array();

112 113 114 115 116 117 118 119 120 121
  /**
   * 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();

122 123
  /**
   * Constructs a new Entity plugin manager.
124
   *
125 126 127
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
128 129 130 131
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend to use.
132
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
133
   *   The language manager.
134 135
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
   *   The string translationManager.
136 137
   * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
   *   The class resolver.
138
   */
139
  public function __construct(\Traversable $namespaces, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, TranslationInterface $translation_manager, ClassResolverInterface $class_resolver) {
140
    parent::__construct('Entity', $namespaces, $module_handler, 'Drupal\Core\Entity\Annotation\EntityType');
141

142 143
    $this->setCacheBackend($cache, $language_manager, 'entity_type:', array('entity_types' => TRUE));
    $this->alterInfo('entity_type');
144

145
    $this->translationManager = $translation_manager;
146
    $this->classResolver = $class_resolver;
147 148
  }

149 150 151 152 153 154 155
  /**
   * {@inheritdoc}
   */
  public function clearCachedDefinitions() {
    parent::clearCachedDefinitions();

    $this->bundleInfo = NULL;
156
    $this->displayModeInfo = array();
157
    $this->extraFields = array();
158 159
  }

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
  /**
   * {@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;
  }

181
  /**
182
   * {@inheritdoc}
183
   */
184 185
  public function getDefinition($entity_type_id, $exception_on_invalid = TRUE) {
    if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
186
      return $entity_type;
187
    }
188 189 190 191
    elseif (!$exception_on_invalid) {
      return NULL;
    }

192
    throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));
193 194
  }

195
  /**
196
   * {@inheritdoc}
197
   */
198
  public function hasController($entity_type, $controller_type) {
199
    if ($definition = $this->getDefinition($entity_type, FALSE)) {
200
      return $definition->hasControllerClass($controller_type);
201
    }
202
    return FALSE;
203 204 205
  }

  /**
206
   * {@inheritdoc}
207
   */
208
  public function getStorage($entity_type) {
209
    return $this->getController($entity_type, 'storage', 'getStorageClass');
210 211 212
  }

  /**
213
   * {@inheritdoc}
214
   */
215 216
  public function getListBuilder($entity_type) {
    return $this->getController($entity_type, 'list_builder', 'getListBuilderClass');
217 218 219
  }

  /**
220
   * {@inheritdoc}
221
   */
222
  public function getFormObject($entity_type, $operation) {
223
    if (!isset($this->controllers['form'][$operation][$entity_type])) {
224 225 226
      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));
      }
227 228

      $controller = $this->classResolver->getInstanceFromDefinition($class);
229 230

      $controller
231
        ->setStringTranslation($this->translationManager)
232 233 234
        ->setModuleHandler($this->moduleHandler)
        ->setOperation($operation);
      $this->controllers['form'][$operation][$entity_type] = $controller;
235 236 237 238 239
    }
    return $this->controllers['form'][$operation][$entity_type];
  }

  /**
240
   * {@inheritdoc}
241
   */
242
  public function getViewBuilder($entity_type) {
243
    return $this->getController($entity_type, 'view_builder', 'getViewBuilderClass');
244 245 246
  }

  /**
247
   * {@inheritdoc}
248 249
   */
  public function getAccessController($entity_type) {
250
    return $this->getController($entity_type, 'access', 'getAccessClass');
251 252 253 254 255 256
  }

  /**
   * Creates a new controller instance.
   *
   * @param string $entity_type
257
   *   The entity type for this controller.
258 259
   * @param string $controller_type
   *   The controller type to create an instance for.
260 261
   * @param string $controller_class_getter
   *   (optional) The method to call on the entity type object to get the controller class.
262
   *
263
   * @return mixed
264
   *   A controller instance.
265 266
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
267
   */
268
  public function getController($entity_type, $controller_type, $controller_class_getter = NULL) {
269
    if (!isset($this->controllers[$controller_type][$entity_type])) {
270
      $definition = $this->getDefinition($entity_type);
271 272
      if ($controller_class_getter) {
        $class = $definition->{$controller_class_getter}();
273 274
      }
      else {
275 276 277 278 279 280 281 282 283 284 285 286 287 288
        $class = $definition->getControllerClass($controller_type);
      }
      if (!$class) {
        throw new InvalidPluginDefinitionException($entity_type, sprintf('The "%s" entity type did not specify a %s class.', $entity_type, $controller_type));
      }
      if (is_subclass_of($class, 'Drupal\Core\Entity\EntityControllerInterface')) {
        $controller = $class::createInstance($this->container, $definition);
      }
      else {
        $controller = new $class($definition);
      }
      if (method_exists($controller, 'setModuleHandler')) {
        $controller->setModuleHandler($this->moduleHandler);
      }
289 290
      if (method_exists($controller, 'setStringTranslation')) {
        $controller->setStringTranslation($this->translationManager);
291
      }
292
      $this->controllers[$controller_type][$entity_type] = $controller;
293
    }
294
    return $this->controllers[$controller_type][$entity_type];
295 296
  }

297
  /**
298
   * {@inheritdoc}
299
   */
300
  public function getAdminRouteInfo($entity_type_id, $bundle) {
301
    if (($entity_type = $this->getDefinition($entity_type_id, FALSE)) && $admin_form = $entity_type->getLinkTemplate('admin-form')) {
302 303 304
      return array(
        'route_name' => $admin_form,
        'route_parameters' => array(
305
          $entity_type->getBundleEntityType() => $bundle,
306 307
        ),
      );
308
    }
309 310
  }

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

349 350 351 352 353
    // 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())));
    }

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

365 366 367 368 369 370 371
    // 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) {
372 373
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
374 375 376 377 378 379 380
          if ($definition instanceof FieldDefinition) {
            $definition->setProvider($module);
          }
          $base_field_definitions[$field_name] = $definition;
        }
      }
    }
381 382 383 384 385 386 387 388 389 390 391 392

    // Automatically set the field name for non-configurable fields.
    foreach ($base_field_definitions as $field_name => $base_field_definition) {
      if ($base_field_definition instanceof FieldDefinition) {
        $base_field_definition->setName($field_name);
        $base_field_definition->setTargetEntityTypeId($entity_type_id);
      }
    }

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

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

    // Allow the entity class to override the base fields.
    $bundle_field_definitions = $class::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions);
453 454
    $provider = $entity_type->getProvider();
    foreach ($bundle_field_definitions as $definition) {
455 456
      // @todo Remove this check once FieldDefinitionInterface exposes a proper
      //  provider setter. See https://drupal.org/node/2225961.
457 458 459 460
      if ($definition instanceof FieldDefinition) {
        $definition->setProvider($provider);
      }
    }
461

462 463 464 465 466 467 468
    // 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) {
469 470
          // @todo Remove this check once FieldDefinitionInterface exposes a
          //  proper provider setter. See https://drupal.org/node/2225961.
471 472 473 474 475 476 477
          if ($definition instanceof FieldDefinition) {
            $definition->setProvider($module);
          }
          $bundle_field_definitions[$field_name] = $definition;
        }
      }
    }
478 479 480 481 482 483

    // Automatically set the field name for non-configurable fields.
    foreach ($bundle_field_definitions as $field_name => $field_definition) {
      if ($field_definition instanceof FieldDefinition) {
        $field_definition->setName($field_name);
        $field_definition->setTargetEntityTypeId($entity_type_id);
484 485
      }
    }
486 487 488 489 490

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

    return $bundle_field_definitions;
491 492
  }

493 494 495 496 497 498 499 500 501 502 503 504 505 506
  /**
   * {@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;
507
      if ($cache = $this->cacheBackend->get($cid)) {
508 509 510 511 512
        $field_storage_definitions = $cache->data;
      }
      else {
        // Rebuild the definitions and put it into the cache.
        $field_storage_definitions = $this->buildFieldStorageDefinitions($entity_type_id);
513
        $this->cacheBackend->set($cid, $field_storage_definitions, Cache::PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
514 515 516 517 518 519
      }
      $this->fieldStorageDefinitions[$entity_type_id] += $field_storage_definitions;
    }
    return $this->fieldStorageDefinitions[$entity_type_id];
  }

520 521 522 523 524 525 526
  /**
   * {@inheritdoc}
   */
  public function getFieldMap() {
    if (!$this->fieldMap) {
      // Not prepared, try to load from cache.
      $cid = 'entity_field_map';
527
      if ($cache = $this->cacheBackend->get($cid)) {
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        $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;
              }
            }
          }
        }

543
        $this->cacheBackend->set($cid, $this->fieldMap, Cache::PERMANENT, array('entity_types' => TRUE, 'entity_field_info' => TRUE));
544 545 546 547 548
      }
    }
    return $this->fieldMap;
  }

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
  /**
   * 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.
          if ($definition instanceof FieldDefinition) {
            $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;
  }

586
  /**
587
   * {@inheritdoc}
588 589
   */
  public function clearCachedFieldDefinitions() {
590 591
    $this->baseFieldDefinitions = array();
    $this->fieldDefinitions = array();
592
    $this->fieldStorageDefinitions = array();
593
    $this->fieldMap = array();
594
    Cache::deleteTags(array('entity_field_info' => TRUE));
595 596
  }

597
  /**
598
   * {@inheritdoc}
599 600 601 602 603 604 605
   */
  public function getBundleInfo($entity_type) {
    $bundle_info = $this->getAllBundleInfo();
    return isset($bundle_info[$entity_type]) ? $bundle_info[$entity_type] : array();
  }

  /**
606
   * {@inheritdoc}
607 608 609
   */
  public function getAllBundleInfo() {
    if (!isset($this->bundleInfo)) {
610
      $langcode = $this->languageManager->getCurrentLanguage()->id;
611
      if ($cache = $this->cacheBackend->get("entity_bundle_info:$langcode")) {
612 613 614 615
        $this->bundleInfo = $cache->data;
      }
      else {
        $this->bundleInfo = $this->moduleHandler->invokeAll('entity_bundle_info');
616 617
        // First look for entity types that act as bundles for others, load them
        // and add them as bundles.
618
        foreach ($this->getDefinitions() as $type => $entity_type) {
619 620 621 622 623 624 625 626
          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.
627
          if (!isset($this->bundleInfo[$type])) {
628
            $this->bundleInfo[$type][$type]['label'] = $entity_type->getLabel();
629 630 631
          }
        }
        $this->moduleHandler->alter('entity_bundle_info', $this->bundleInfo);
632
        $this->cacheBackend->set("entity_bundle_info:$langcode", $this->bundleInfo, Cache::PERMANENT, array('entity_types' => TRUE));
633 634 635 636 637 638
      }
    }

    return $this->bundleInfo;
  }

639 640 641 642 643 644 645 646 647 648 649 650 651
  /**
   * {@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;
652
    $cached = $this->cacheBackend->get($cache_id);
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    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;
668
    $this->cacheBackend->set($cache_id, $info, Cache::PERMANENT, array(
669 670 671 672 673 674
      'entity_field_info' => TRUE,
    ));

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

675
  /**
676
   * {@inheritdoc}
677
   */
678
  public function getEntityTypeLabels($group = FALSE) {
679
    $options = array();
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    $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;
700 701 702 703 704
    }

    return $options;
  }

705 706 707 708 709 710 711 712
  /**
   * {@inheritdoc}
   */
  public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
    $translation = $entity;

    if ($entity instanceof TranslatableInterface) {
      if (empty($langcode)) {
713
        $langcode = $this->languageManager->getCurrentLanguage(Language::TYPE_CONTENT)->id;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
      }

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

      // Ensure the default language has the proper language code.
      $default_language = $entity->getUntranslated()->language();
      $candidates[$default_language->id] = Language::LANGCODE_DEFAULT;

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

    return $translation;
  }

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
  /**
   * {@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';
      $langcode = $this->languageManager->getCurrentLanguage(Language::TYPE_INTERFACE)->id;
779
      if ($cache = $this->cacheBackend->get("$key:$langcode")) {
780 781 782 783
        $this->displayModeInfo[$display_type] = $cache->data;
      }
      else {
        $this->displayModeInfo[$display_type] = array();
784
        foreach ($this->getStorage($display_type)->loadMultiple() as $display_mode) {
785 786 787 788
          list($display_mode_entity_type, $display_mode_name) = explode('.', $display_mode->id(), 2);
          $this->displayModeInfo[$display_type][$display_mode_entity_type][$display_mode_name] = (array) $display_mode;
        }
        $this->moduleHandler->alter($key, $this->displayModeInfo[$display_type]);
789
        $this->cacheBackend->set("$key:$langcode", $this->displayModeInfo[$display_type], CacheBackendInterface::CACHE_PERMANENT, array('entity_types' => TRUE));
790 791 792 793 794 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 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
      }
    }

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

857
}