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

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

namespace Drupal\Core\Entity;

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

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

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

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

56 57 58 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
  /**
   * 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;

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

102 103 104 105 106 107 108
  /**
   * The string translationManager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $translationManager;

109
  /**
110 111 112 113 114 115
   * Static cache of bundle information.
   *
   * @var array
   */
  protected $bundleInfo;

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

    $this->moduleHandler = $module_handler;
    $this->cache = $cache;
    $this->languageManager = $language_manager;
139
    $this->namespaces = $namespaces;
140
    $this->translationManager = $translation_manager;
141

142
    $this->discovery = new AnnotatedClassDiscovery('Entity', $namespaces, 'Drupal\Core\Entity\Annotation\EntityType');
143
    $this->discovery = new InfoHookDecorator($this->discovery, 'entity_info');
144
    $this->discovery = new AlterDecorator($this->discovery, 'entity_info');
145
    $this->discovery = new CacheDecorator($this->discovery, 'entity_info:' . $this->languageManager->getLanguage(Language::TYPE_INTERFACE)->id, 'cache', CacheBackendInterface::CACHE_PERMANENT, array('entity_info' => TRUE));
146 147
    $this->factory = new DefaultFactory($this->discovery);
    $this->container = $container;
148 149
  }

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

    $this->bundleInfo = NULL;
  }

159
  /**
160
   * {@inheritdoc}
161 162 163
   */
  public function hasController($entity_type, $controller_type) {
    $definition = $this->getDefinition($entity_type);
164
    return !empty($definition['controllers'][$controller_type]);
165 166
  }

167
  /**
168
   * {@inheritdoc}
169 170 171
   */
  public function getControllerClass($entity_type, $controller_type, $nested = NULL) {
    $definition = $this->getDefinition($entity_type);
172 173 174
    if (!$definition) {
      throw new \InvalidArgumentException(sprintf('The %s entity type does not exist.', $entity_type));
    }
175
    $definition = $definition['controllers'];
176 177 178 179
    if (!$definition) {
      throw new \InvalidArgumentException(sprintf('The entity type (%s) does not exist.', $entity_type));
    }

180
    if (empty($definition[$controller_type])) {
181
      throw new \InvalidArgumentException(sprintf('The entity type (%s) did not specify a %s controller.', $entity_type, $controller_type));
182 183 184 185 186 187 188
    }

    $class = $definition[$controller_type];

    // Some class definitions can be nested.
    if (isset($nested)) {
      if (empty($class[$nested])) {
189
        throw new \InvalidArgumentException(sprintf("The entity type (%s) did not specify a %s controller: %s.", $entity_type, $controller_type, $nested));
190 191 192 193 194 195
      }

      $class = $class[$nested];
    }

    if (!class_exists($class)) {
196
      throw new \InvalidArgumentException(sprintf('The entity type (%s) %s controller "%s" does not exist.', $entity_type, $controller_type, $class));
197 198 199 200 201 202
    }

    return $class;
  }

  /**
203
   * {@inheritdoc}
204 205
   */
  public function getStorageController($entity_type) {
206
    return $this->getController($entity_type, 'storage');
207 208 209
  }

  /**
210
   * {@inheritdoc}
211 212 213
   */
  public function getListController($entity_type) {
    if (!isset($this->controllers['listing'][$entity_type])) {
214
      $class = $this->getControllerClass($entity_type, 'list');
215 216 217 218 219 220
      if (in_array('Drupal\Core\Entity\EntityControllerInterface', class_implements($class))) {
        $this->controllers['listing'][$entity_type] = $class::createInstance($this->container, $entity_type, $this->getDefinition($entity_type));
      }
      else {
        $this->controllers['listing'][$entity_type] = new $class($entity_type, $this->getStorageController($entity_type));
      }
221 222 223 224 225
    }
    return $this->controllers['listing'][$entity_type];
  }

  /**
226
   * {@inheritdoc}
227 228 229
   */
  public function getFormController($entity_type, $operation) {
    if (!isset($this->controllers['form'][$operation][$entity_type])) {
230
      $class = $this->getControllerClass($entity_type, 'form', $operation);
231
      if (in_array('Drupal\Core\DependencyInjection\ContainerInjectionInterface', class_implements($class))) {
232
        $controller = $class::create($this->container);
233 234
      }
      else {
235
        $controller = new $class();
236
      }
237 238 239 240 241 242

      $controller
        ->setTranslationManager($this->translationManager)
        ->setModuleHandler($this->moduleHandler)
        ->setOperation($operation);
      $this->controllers['form'][$operation][$entity_type] = $controller;
243 244 245 246 247
    }
    return $this->controllers['form'][$operation][$entity_type];
  }

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

  /**
255
   * {@inheritdoc}
256 257
   */
  public function getAccessController($entity_type) {
258 259 260 261 262
    if (!isset($this->controllers['access'][$entity_type])) {
      $controller = $this->getController($entity_type, 'access');
      $controller->setModuleHandler($this->moduleHandler);
    }
    return $this->controllers['access'][$entity_type];
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  }

  /**
   * Creates a new controller instance.
   *
   * @param string $entity_type
   *   The entity type for this access controller.
   * @param string $controller_type
   *   The controller type to create an instance for.
   *
   * @return mixed.
   *   A controller instance.
   */
  protected function getController($entity_type, $controller_type) {
    if (!isset($this->controllers[$controller_type][$entity_type])) {
      $class = $this->getControllerClass($entity_type, $controller_type);
279
      if (in_array('Drupal\Core\Entity\EntityControllerInterface', class_implements($class))) {
280
        $this->controllers[$controller_type][$entity_type] = $class::createInstance($this->container, $entity_type, $this->getDefinition($entity_type));
281 282
      }
      else {
283
        $this->controllers[$controller_type][$entity_type] = new $class($entity_type, $this->getDefinition($entity_type));
284
      }
285
    }
286
    return $this->controllers[$controller_type][$entity_type];
287 288
  }

289
  /**
290
   * {@inheritdoc}
291 292 293
   */
  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state = array()) {
    $form_state += entity_form_state_defaults($entity, $operation);
294
    $form_id = $form_state['build_info']['callback_object']->getFormId();
295 296 297
    return drupal_build_form($form_id, $form_state);
  }

298
  /**
299
   * {@inheritdoc}
300 301 302 303 304
   */
  public function getAdminPath($entity_type, $bundle) {
    $admin_path = '';
    $entity_info = $this->getDefinition($entity_type);
    // Check for an entity type's admin base path.
305 306 307
    if (isset($entity_info['links']['admin-form'])) {
      $route_parameters[$entity_info['bundle_entity_type']] = $bundle;
      $admin_path = \Drupal::urlGenerator()->getPathFromRoute($entity_info['links']['admin-form'], $route_parameters);
308 309 310 311 312
    }

    return $admin_path;
  }

313
  /**
314
   * {@inheritdoc}
315 316
   */
  public function getAdminRouteInfo($entity_type, $bundle) {
317
    $entity_info = $this->getDefinition($entity_type);
318
    return array(
319
      'route_name' => "field_ui.overview_$entity_type",
320
      'route_parameters' => array(
321
        $entity_info['bundle_entity_type'] => $bundle,
322 323 324 325
      )
    );
  }

326
  /**
327
   * {@inheritdoc}
328 329 330 331
   */
  public function getFieldDefinitions($entity_type, $bundle = NULL) {
    if (!isset($this->entityFieldInfo[$entity_type])) {
      // First, try to load from cache.
332
      $cid = 'entity_field_definitions:' . $entity_type . ':' . $this->languageManager->getLanguage(Language::TYPE_INTERFACE)->id;
333 334 335 336
      if ($cache = $this->cache->get($cid)) {
        $this->entityFieldInfo[$entity_type] = $cache->data;
      }
      else {
337 338
        // @todo: Refactor to allow for per-bundle overrides.
        // See https://drupal.org/node/2114707.
339
        $class = $this->factory->getPluginClass($entity_type, $this->getDefinition($entity_type));
340

341
        $this->entityFieldInfo[$entity_type] = array(
342
          'definitions' => $class::baseFieldDefinitions($entity_type),
343 344 345 346 347 348 349 350 351 352 353 354 355
          // 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);

356
        // Automatically set the field name for non-configurable fields.
357 358 359
        foreach (array('definitions', 'optional') as $key) {
          foreach ($this->entityFieldInfo[$entity_type][$key] as $field_name => &$definition) {
            if ($definition instanceof FieldDefinition) {
360
              $definition->setName($field_name);
361 362 363 364 365
            }
          }
        }

        // Invoke alter hooks.
366 367 368
        $hooks = array('entity_field_info', $entity_type . '_field_info');
        $this->moduleHandler->alter($hooks, $this->entityFieldInfo[$entity_type], $entity_type);

369
        // Ensure all basic fields are not defined as translatable.
370 371 372 373
        $entity_info = $this->getDefinition($entity_type);
        $keys = array_intersect_key(array_filter($entity_info['entity_keys']), array_flip(array('id', 'revision', 'uuid', 'bundle')));
        $untranslatable_fields = array_flip(array('langcode') + $keys);
        foreach (array('definitions', 'optional') as $key) {
374
          foreach ($this->entityFieldInfo[$entity_type][$key] as $field_name => &$definition) {
375 376
            if (isset($untranslatable_fields[$field_name]) && $definition->isTranslatable()) {
              throw new \LogicException(format_string('The @field field cannot be translatable.', array('@field' => $definition->getLabel())));
377 378
            }
          }
379
        }
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        $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];
    }
  }

  /**
401
   * {@inheritdoc}
402 403 404 405 406 407 408
   */
  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);
  }

  /**
409
   * {@inheritdoc}
410 411 412 413 414 415 416
   */
  public function clearCachedFieldDefinitions() {
    unset($this->entityFieldInfo);
    unset($this->fieldDefinitions);
    $this->cache->deleteTags(array('entity_field_info' => TRUE));
  }

417
  /**
418
   * {@inheritdoc}
419 420 421 422 423 424 425
   */
  public function getBundleInfo($entity_type) {
    $bundle_info = $this->getAllBundleInfo();
    return isset($bundle_info[$entity_type]) ? $bundle_info[$entity_type] : array();
  }

  /**
426
   * {@inheritdoc}
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
   */
  public function getAllBundleInfo() {
    if (!isset($this->bundleInfo)) {
      $langcode = $this->languageManager->getLanguage(Language::TYPE_INTERFACE)->id;
      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])) {
            $this->bundleInfo[$type][$type]['label'] = $entity_info['label'];
          }
        }
        $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;
  }

450
  /**
451
   * {@inheritdoc}
452 453 454 455 456 457 458 459 460 461
   */
  public function getEntityTypeLabels() {
    $options = array();
    foreach ($this->getDefinitions() as $entity_type => $definition) {
      $options[$entity_type] = $definition['label'];
    }

    return $options;
  }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
  /**
   * {@inheritdoc}
   */
  public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
    $translation = $entity;

    if ($entity instanceof TranslatableInterface) {
      if (empty($langcode)) {
        $langcode = $this->languageManager->getLanguage(Language::TYPE_CONTENT)->id;
      }

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

495
}