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

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

namespace Drupal\Core\Entity;

10 11
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\UnknownPluginException;
12
use Drupal\Component\Plugin\PluginManagerBase;
13
use Drupal\Component\Utility\NestedArray;
14
use Drupal\Component\Utility\String;
15
use Drupal\Core\Field\FieldDefinition;
16
use Drupal\Core\Cache\Cache;
17
use Drupal\Core\Cache\CacheBackendInterface;
18 19
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManager;
20
use Drupal\Core\Language\Language;
21
use Drupal\Core\Plugin\Discovery\AlterDecorator;
22
use Drupal\Core\Plugin\Discovery\CacheDecorator;
23
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
24
use Drupal\Core\Plugin\Discovery\InfoHookDecorator;
25
use Drupal\Core\StringTranslation\TranslationInterface;
26
use Drupal\Core\TypedData\TranslatableInterface;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28 29 30 31

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

45 46 47 48 49 50 51
  /**
   * The injection container that should be passed into the controller factory.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

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

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The cache backend to use.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

  /**
   * An array of field information per entity type, i.e. containing definitions.
   *
   * @var array
   *
   * @see hook_entity_field_info()
   */
  protected $entityFieldInfo;

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

96 97 98
  /**
   * The root paths.
   *
99
   * @see self::__construct().
100 101 102 103 104
   *
   * @var \Traversable
   */
  protected $namespaces;

105 106 107 108 109 110 111
  /**
   * The string translationManager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

112
  /**
113 114 115 116 117 118
   * Static cache of bundle information.
   *
   * @var array
   */
  protected $bundleInfo;

119 120
  /**
   * Constructs a new Entity plugin manager.
121
   *
122 123 124
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
125 126
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The service container this object should use.
127 128 129 130 131 132
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend to use.
   * @param \Drupal\Core\Language\LanguageManager $language_manager
   *   The language manager.
133 134
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
   *   The string translationManager.
135
   */
136
  public function __construct(\Traversable $namespaces, ContainerInterface $container, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManager $language_manager, TranslationInterface $translation_manager) {
137
    // Allow the plugin definition to be altered by hook_entity_info_alter().
138 139 140 141

    $this->moduleHandler = $module_handler;
    $this->cache = $cache;
    $this->languageManager = $language_manager;
142
    $this->namespaces = $namespaces;
143
    $this->translationManager = $translation_manager;
144

145
    $this->discovery = new AnnotatedClassDiscovery('Entity', $namespaces, 'Drupal\Core\Entity\Annotation\EntityType');
146
    $this->discovery = new InfoHookDecorator($this->discovery, 'entity_info');
147
    $this->discovery = new AlterDecorator($this->discovery, 'entity_info');
148
    $this->discovery = new CacheDecorator($this->discovery, 'entity_info:' . $this->languageManager->getCurrentLanguage()->id, 'cache', CacheBackendInterface::CACHE_PERMANENT, array('entity_info' => TRUE));
149
    $this->container = $container;
150 151
  }

152 153 154 155 156 157 158 159 160
  /**
   * {@inheritdoc}
   */
  public function clearCachedDefinitions() {
    parent::clearCachedDefinitions();

    $this->bundleInfo = NULL;
  }

161
  /**
162
   * {@inheritdoc}
163
   */
164 165 166
  public function getDefinition($entity_type_id, $exception_on_invalid = FALSE) {
    if (($entity_type = parent::getDefinition($entity_type_id)) && class_exists($entity_type->getClass())) {
      return $entity_type;
167
    }
168 169 170 171 172
    elseif (!$exception_on_invalid) {
      return NULL;
    }

    throw new UnknownPluginException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));
173 174
  }

175
  /**
176
   * {@inheritdoc}
177
   */
178 179 180
  public function hasController($entity_type, $controller_type) {
    if ($definition = $this->getDefinition($entity_type)) {
      return $definition->hasControllerClass($controller_type);
181
    }
182
    return FALSE;
183 184 185
  }

  /**
186
   * {@inheritdoc}
187 188
   */
  public function getStorageController($entity_type) {
189
    return $this->getController($entity_type, 'storage', 'getStorageClass');
190 191 192
  }

  /**
193
   * {@inheritdoc}
194 195
   */
  public function getListController($entity_type) {
196
    return $this->getController($entity_type, 'list', 'getListClass');
197 198 199
  }

  /**
200
   * {@inheritdoc}
201 202 203
   */
  public function getFormController($entity_type, $operation) {
    if (!isset($this->controllers['form'][$operation][$entity_type])) {
204 205 206
      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));
      }
207
      if (in_array('Drupal\Core\DependencyInjection\ContainerInjectionInterface', class_implements($class))) {
208
        $controller = $class::create($this->container);
209 210
      }
      else {
211
        $controller = new $class();
212
      }
213 214 215 216 217 218

      $controller
        ->setTranslationManager($this->translationManager)
        ->setModuleHandler($this->moduleHandler)
        ->setOperation($operation);
      $this->controllers['form'][$operation][$entity_type] = $controller;
219 220 221 222 223
    }
    return $this->controllers['form'][$operation][$entity_type];
  }

  /**
224
   * {@inheritdoc}
225
   */
226
  public function getViewBuilder($entity_type) {
227
    return $this->getController($entity_type, 'view_builder', 'getViewBuilderClass');
228 229 230
  }

  /**
231
   * {@inheritdoc}
232 233
   */
  public function getAccessController($entity_type) {
234
    return $this->getController($entity_type, 'access', 'getAccessClass');
235 236 237 238 239 240
  }

  /**
   * Creates a new controller instance.
   *
   * @param string $entity_type
241
   *   The entity type for this controller.
242 243
   * @param string $controller_type
   *   The controller type to create an instance for.
244 245
   * @param string $controller_class_getter
   *   (optional) The method to call on the entity type object to get the controller class.
246
   *
247
   * @return mixed
248
   *   A controller instance.
249 250
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
251
   */
252
  public function getController($entity_type, $controller_type, $controller_class_getter = NULL) {
253
    if (!isset($this->controllers[$controller_type][$entity_type])) {
254 255 256
      $definition = $this->getDefinition($entity_type, TRUE);
      if ($controller_class_getter) {
        $class = $definition->{$controller_class_getter}();
257 258
      }
      else {
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        $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);
      }
      if (method_exists($controller, 'setTranslationManager')) {
        $controller->setTranslationManager($this->translationManager);
275
      }
276
      $this->controllers[$controller_type][$entity_type] = $controller;
277
    }
278
    return $this->controllers[$controller_type][$entity_type];
279 280
  }

281
  /**
282
   * {@inheritdoc}
283 284
   */
  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state = array()) {
285 286 287 288 289 290 291 292 293 294
    $form_state['build_info'] = isset($form_state['build_info']) ? $form_state['build_info'] : array();
    $controller = $this->getFormController($entity->entityType(), $operation);
    $controller->setEntity($entity);
    $form_state['build_info'] += array(
      'callback_object' => $controller,
      'base_form_id' => $controller->getBaseFormID(),
      'args' => array(),
    );
    $form_id = $controller->getFormID();
    return \Drupal::formBuilder()->buildForm($form_id, $form_state);
295 296
  }

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

311
  /**
312
   * {@inheritdoc}
313 314 315 316
   */
  public function getFieldDefinitions($entity_type, $bundle = NULL) {
    if (!isset($this->entityFieldInfo[$entity_type])) {
      // First, try to load from cache.
317
      $cid = 'entity_field_definitions:' . $entity_type . ':' . $this->languageManager->getCurrentLanguage()->id;
318 319 320 321
      if ($cache = $this->cache->get($cid)) {
        $this->entityFieldInfo[$entity_type] = $cache->data;
      }
      else {
322 323
        // @todo: Refactor to allow for per-bundle overrides.
        // See https://drupal.org/node/2114707.
324
        $entity_info = $this->getDefinition($entity_type);
325
        $class = $entity_info->getClass();
326

327
        $this->entityFieldInfo[$entity_type] = array(
328
          'definitions' => $class::baseFieldDefinitions($entity_type),
329 330 331 332 333 334 335 336 337 338 339 340 341
          // Contains definitions of optional (per-bundle) fields.
          'optional' => array(),
          // An array keyed by bundle name containing the optional fields added
          // by the bundle.
          'bundle map' => array(),
        );

        // Invoke hooks.
        $result = $this->moduleHandler->invokeAll($entity_type . '_field_info');
        $this->entityFieldInfo[$entity_type] = NestedArray::mergeDeep($this->entityFieldInfo[$entity_type], $result);
        $result = $this->moduleHandler->invokeAll('entity_field_info', array($entity_type));
        $this->entityFieldInfo[$entity_type] = NestedArray::mergeDeep($this->entityFieldInfo[$entity_type], $result);

342
        // Automatically set the field name for non-configurable fields.
343 344 345
        foreach (array('definitions', 'optional') as $key) {
          foreach ($this->entityFieldInfo[$entity_type][$key] as $field_name => &$definition) {
            if ($definition instanceof FieldDefinition) {
346
              $definition->setName($field_name);
347 348 349 350 351
            }
          }
        }

        // Invoke alter hooks.
352 353 354
        $hooks = array('entity_field_info', $entity_type . '_field_info');
        $this->moduleHandler->alter($hooks, $this->entityFieldInfo[$entity_type], $entity_type);

355
        // Ensure all basic fields are not defined as translatable.
356
        $keys = array_intersect_key(array_filter($entity_info->getKeys()), array_flip(array('id', 'revision', 'uuid', 'bundle')));
357 358
        $untranslatable_fields = array_flip(array('langcode') + $keys);
        foreach (array('definitions', 'optional') as $key) {
359
          foreach ($this->entityFieldInfo[$entity_type][$key] as $field_name => &$definition) {
360
            if (isset($untranslatable_fields[$field_name]) && $definition->isTranslatable()) {
361
              throw new \LogicException(String::format('The @field field cannot be translatable.', array('@field' => $definition->getLabel())));
362 363
            }
          }
364
        }
365

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
        $this->cache->set($cid, $this->entityFieldInfo[$entity_type], CacheBackendInterface::CACHE_PERMANENT, array('entity_info' => TRUE, 'entity_field_info' => TRUE));
      }
    }

    if (!$bundle) {
      return $this->entityFieldInfo[$entity_type]['definitions'];
    }
    else {
      // Add in per-bundle fields.
      if (!isset($this->fieldDefinitions[$entity_type][$bundle])) {
        $this->fieldDefinitions[$entity_type][$bundle] = $this->entityFieldInfo[$entity_type]['definitions'];
        if (isset($this->entityFieldInfo[$entity_type]['bundle map'][$bundle])) {
          $this->fieldDefinitions[$entity_type][$bundle] += array_intersect_key($this->entityFieldInfo[$entity_type]['optional'], array_flip($this->entityFieldInfo[$entity_type]['bundle map'][$bundle]));
        }
      }
      return $this->fieldDefinitions[$entity_type][$bundle];
    }
  }

  /**
386
   * {@inheritdoc}
387 388 389 390 391 392 393
   */
  public function getFieldDefinitionsByConstraints($entity_type, array $constraints) {
    // @todo: Add support for specifying multiple bundles.
    return $this->getFieldDefinitions($entity_type, isset($constraints['Bundle']) ? $constraints['Bundle'] : NULL);
  }

  /**
394
   * {@inheritdoc}
395 396 397 398
   */
  public function clearCachedFieldDefinitions() {
    unset($this->entityFieldInfo);
    unset($this->fieldDefinitions);
399
    Cache::deleteTags(array('entity_field_info' => TRUE));
400 401
  }

402
  /**
403
   * {@inheritdoc}
404 405 406 407 408 409 410
   */
  public function getBundleInfo($entity_type) {
    $bundle_info = $this->getAllBundleInfo();
    return isset($bundle_info[$entity_type]) ? $bundle_info[$entity_type] : array();
  }

  /**
411
   * {@inheritdoc}
412 413 414
   */
  public function getAllBundleInfo() {
    if (!isset($this->bundleInfo)) {
415
      $langcode = $this->languageManager->getCurrentLanguage()->id;
416 417 418 419 420 421 422 423
      if ($cache = $this->cache->get("entity_bundle_info:$langcode")) {
        $this->bundleInfo = $cache->data;
      }
      else {
        $this->bundleInfo = $this->moduleHandler->invokeAll('entity_bundle_info');
        // If no bundles are provided, use the entity type name and label.
        foreach ($this->getDefinitions() as $type => $entity_info) {
          if (!isset($this->bundleInfo[$type])) {
424
            $this->bundleInfo[$type][$type]['label'] = $entity_info->getLabel();
425 426 427 428 429 430 431 432 433 434
          }
        }
        $this->moduleHandler->alter('entity_bundle_info', $this->bundleInfo);
        $this->cache->set("entity_bundle_info:$langcode", $this->bundleInfo, CacheBackendInterface::CACHE_PERMANENT, array('entity_info' => TRUE));
      }
    }

    return $this->bundleInfo;
  }

435
  /**
436
   * {@inheritdoc}
437 438 439 440
   */
  public function getEntityTypeLabels() {
    $options = array();
    foreach ($this->getDefinitions() as $entity_type => $definition) {
441
      $options[$entity_type] = $definition->getLabel();
442 443 444 445 446
    }

    return $options;
  }

447 448 449 450 451 452 453 454
  /**
   * {@inheritdoc}
   */
  public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
    $translation = $entity;

    if ($entity instanceof TranslatableInterface) {
      if (empty($langcode)) {
455
        $langcode = $this->languageManager->getCurrentLanguage(Language::TYPE_CONTENT)->id;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
      }

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

480
}