EntityManager.php 17.3 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 13 14
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManager;
15
use Drupal\Core\Language\Language;
16
use Drupal\Core\Plugin\Discovery\AlterDecorator;
17
use Drupal\Core\Plugin\Discovery\CacheDecorator;
18
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
19
use Drupal\Core\Plugin\Discovery\InfoHookDecorator;
20
use Drupal\Core\Cache\CacheBackendInterface;
21
use Drupal\Core\StringTranslation\TranslationInterface;
22
use Symfony\Component\DependencyInjection\ContainerInterface;
23 24 25 26

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

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

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

54 55 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
  /**
   * 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;

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

98 99
  /**
   * Constructs a new Entity plugin manager.
100
   *
101 102 103
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
104 105
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The service container this object should use.
106 107 108 109 110 111
   * @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.
112 113
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
   *   The string translationManager.
114
   */
115
  public function __construct(\Traversable $namespaces, ContainerInterface $container, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManager $language_manager, TranslationInterface $translation_manager) {
116
    // Allow the plugin definition to be altered by hook_entity_info_alter().
117 118 119
    $annotation_namespaces = array(
      'Drupal\Core\Entity\Annotation' => DRUPAL_ROOT . '/core/lib',
    );
120 121 122 123

    $this->moduleHandler = $module_handler;
    $this->cache = $cache;
    $this->languageManager = $language_manager;
124
    $this->translationManager = $translation_manager;
125

126
    $this->discovery = new AnnotatedClassDiscovery('Entity', $namespaces, $annotation_namespaces, 'Drupal\Core\Entity\Annotation\EntityType');
127
    $this->discovery = new InfoHookDecorator($this->discovery, 'entity_info');
128
    $this->discovery = new AlterDecorator($this->discovery, 'entity_info');
129
    $this->discovery = new CacheDecorator($this->discovery, 'entity_info:' . $this->languageManager->getLanguage(Language::TYPE_INTERFACE)->id, 'cache', CacheBackendInterface::CACHE_PERMANENT, array('entity_info' => TRUE));
130

131
    $this->factory = new DefaultFactory($this->discovery);
132
    $this->container = $container;
133 134
  }

135 136 137 138 139 140 141 142 143 144 145 146 147
  /**
   * Checks whether a certain entity type has a certain controller.
   *
   * @param string $entity_type
   *   The name of the entity type.
   * @param string $controller_type
   *   The name of the controller.
   *
   * @return bool
   *   Returns TRUE if the entity type has the controller, else FALSE.
   */
  public function hasController($entity_type, $controller_type) {
    $definition = $this->getDefinition($entity_type);
148
    return !empty($definition['controllers'][$controller_type]);
149 150
  }

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  /**
   * Returns an entity controller class.
   *
   * @param string $entity_type
   *   The name of the entity type
   * @param string $controller_type
   *   The name of the controller.
   * @param string|null $nested
   *   (optional) If this controller definition is nested, the name of the key.
   *   Defaults to NULL.
   *
   * @return string
   *   The class name for this controller instance.
   */
  public function getControllerClass($entity_type, $controller_type, $nested = NULL) {
    $definition = $this->getDefinition($entity_type);
167
    $definition = $definition['controllers'];
168 169 170 171
    if (!$definition) {
      throw new \InvalidArgumentException(sprintf('The entity type (%s) does not exist.', $entity_type));
    }

172
    if (empty($definition[$controller_type])) {
173
      throw new \InvalidArgumentException(sprintf('The entity type (%s) did not specify a %s controller.', $entity_type, $controller_type));
174 175 176 177 178 179 180
    }

    $class = $definition[$controller_type];

    // Some class definitions can be nested.
    if (isset($nested)) {
      if (empty($class[$nested])) {
181
        throw new \InvalidArgumentException(sprintf("The entity type (%s) did not specify a %s controller: %s.", $entity_type, $controller_type, $nested));
182 183 184 185 186 187
      }

      $class = $class[$nested];
    }

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

    return $class;
  }

  /**
   * Creates a new storage controller instance.
   *
   * @param string $entity_type
   *   The entity type for this storage controller.
   *
   * @return \Drupal\Core\Entity\EntityStorageControllerInterface
   *   A storage controller instance.
   */
  public function getStorageController($entity_type) {
204
    return $this->getController($entity_type, 'storage');
205 206 207 208 209 210 211 212 213 214 215 216 217
  }

  /**
   * Creates a new list controller instance.
   *
   * @param string $entity_type
   *   The entity type for this list controller.
   *
   * @return \Drupal\Core\Entity\EntityListControllerInterface
   *   A list controller instance.
   */
  public function getListController($entity_type) {
    if (!isset($this->controllers['listing'][$entity_type])) {
218
      $class = $this->getControllerClass($entity_type, 'list');
219 220 221 222 223 224
      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));
      }
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    }
    return $this->controllers['listing'][$entity_type];
  }

  /**
   * Creates a new form controller instance.
   *
   * @param string $entity_type
   *   The entity type for this form controller.
   * @param string $operation
   *   The name of the operation to use, e.g., 'default'.
   *
   * @return \Drupal\Core\Entity\EntityFormControllerInterface
   *   A form controller instance.
   */
  public function getFormController($entity_type, $operation) {
    if (!isset($this->controllers['form'][$operation][$entity_type])) {
242
      $class = $this->getControllerClass($entity_type, 'form', $operation);
243 244
      if (in_array('Drupal\Core\Controller\ControllerInterface', class_implements($class))) {
        $controller = $class::create($this->container);
245 246
      }
      else {
247
        $controller = new $class();
248
      }
249 250 251 252 253 254

      $controller
        ->setTranslationManager($this->translationManager)
        ->setModuleHandler($this->moduleHandler)
        ->setOperation($operation);
      $this->controllers['form'][$operation][$entity_type] = $controller;
255 256 257 258 259 260 261 262 263 264 265 266 267 268
    }
    return $this->controllers['form'][$operation][$entity_type];
  }

  /**
   * Creates a new render controller instance.
   *
   * @param string $entity_type
   *   The entity type for this render controller.
   *
   * @return \Drupal\Core\Entity\EntityRenderControllerInterface.
   *   A render controller instance.
   */
  public function getRenderController($entity_type) {
269
    return $this->getController($entity_type, 'render');
270 271 272 273 274 275 276 277
  }

  /**
   * Creates a new access controller instance.
   *
   * @param string $entity_type
   *   The entity type for this access controller.
   *
278
   * @return \Drupal\Core\Entity\EntityAccessControllerInterface.
279 280 281
   *   A access controller instance.
   */
  public function getAccessController($entity_type) {
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    return $this->getController($entity_type, 'access');
  }

  /**
   * 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);
299
      if (in_array('Drupal\Core\Entity\EntityControllerInterface', class_implements($class))) {
300
        $this->controllers[$controller_type][$entity_type] = $class::createInstance($this->container, $entity_type, $this->getDefinition($entity_type));
301 302
      }
      else {
303
        $this->controllers[$controller_type][$entity_type] = new $class($entity_type);
304
      }
305
    }
306
    return $this->controllers[$controller_type][$entity_type];
307 308
  }

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  /**
   * Returns the built and processed entity form for the given entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to be created or edited.
   * @param string $operation
   *   (optional) The operation identifying the form variation to be returned.
   *   Defaults to 'default'.
   * @param array $form_state
   *   (optional) An associative array containing the current state of the form.
   *   Use this to pass additional information to the form, such as the
   *   langcode. Defaults to an empty array.
   * @code
   *   $form_state['langcode'] = $langcode;
   *   $manager = Drupal::entityManager();
   *   $form = $manager->getForm($entity, 'default', $form_state);
   * @endcode
   *
   * @return array
   *   The processed form for the given entity and operation.
   */
  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state = array()) {
    $form_state += entity_form_state_defaults($entity, $operation);
    $form_id = $form_state['build_info']['callback_object']->getFormID();
    return drupal_build_form($form_id, $form_state);
  }

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
  /**
   * Returns the administration path for an entity type's bundle.
   *
   * @param string $entity_type
   *   The entity type.
   * @param string $bundle
   *   The name of the bundle.
   *
   * @return string
   *   The administration path for an entity type bundle, if it exists.
   */
  public function getAdminPath($entity_type, $bundle) {
    $admin_path = '';
    $entity_info = $this->getDefinition($entity_type);
    // Check for an entity type's admin base path.
    if (isset($entity_info['route_base_path'])) {
      // If the entity type has a bundle prefix, strip it out of the path.
      if (isset($entity_info['bundle_prefix'])) {
        $bundle = str_replace($entity_info['bundle_prefix'], '', $bundle);
      }
      // Replace any dynamic 'bundle' portion of the path with the actual bundle.
      $admin_path = str_replace('{bundle}', $bundle, $entity_info['route_base_path']);
    }

    return $admin_path;
  }

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  /**
   * Gets an array of entity field definitions.
   *
   * If a bundle is passed, fields specific to this bundle are included. Entity
   * fields are always multi-valued, so 'list' is TRUE for each returned field
   * definition.
   *
   * @param string $entity_type
   *   The entity type to get field definitions for.
   * @param string $bundle
   *   (optional) The entity bundle for which to get field definitions. If NULL
   *   is passed, no bundle-specific fields are included. Defaults to NULL.
   *
   * @return array
   *   An array of field definitions of entity fields, keyed by field
   *   name. In addition to the typed data definition keys as described at
   *   \Drupal\Core\TypedData\TypedDataManager::create() the following keys are
   *   supported:
   *   - queryable: Whether the field is queryable via QueryInterface.
   *     Defaults to TRUE if 'computed' is FALSE or not set, to FALSE otherwise.
   *   - translatable: Whether the field is translatable. Defaults to FALSE.
   *   - configurable: A boolean indicating whether the field is configurable
   *     via field.module. Defaults to FALSE.
   *
   * @see \Drupal\Core\TypedData\TypedDataManager::create()
   * @see \Drupal\Core\Entity\EntityManager::getFieldDefinitionsByConstraints()
   */
  public function getFieldDefinitions($entity_type, $bundle = NULL) {
    if (!isset($this->entityFieldInfo[$entity_type])) {
      // First, try to load from cache.
393
      $cid = 'entity_field_definitions:' . $entity_type . ':' . $this->languageManager->getLanguage(Language::TYPE_INTERFACE)->id;
394 395 396 397
      if ($cache = $this->cache->get($cid)) {
        $this->entityFieldInfo[$entity_type] = $cache->data;
      }
      else {
398
        $class = $this->factory->getPluginClass($entity_type, $this->getDefinition($entity_type));
399
        $this->entityFieldInfo[$entity_type] = array(
400
          'definitions' => $class::baseFieldDefinitions($entity_type),
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
          // 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);

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

        // Enforce fields to be multiple by default.
        foreach ($this->entityFieldInfo[$entity_type]['definitions'] as &$definition) {
          $definition['list'] = TRUE;
        }
        foreach ($this->entityFieldInfo[$entity_type]['optional'] as &$definition) {
          $definition['list'] = TRUE;
        }
        $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];
    }
  }

  /**
   * Gets an array of entity field definitions based on validation constraints.
   *
   * @param string $entity_type
   *   The entity type to get field definitions for.
   * @param array $constraints
   *   An array of entity constraints as used for entities in typed data
   *   definitions, i.e. an array optionally including a 'Bundle' key.
   *   For example the constraints used by an entity reference could be:
   *   @code
   *   array(
   *     'Bundle' => 'article',
   *   )
   *   @endcode
   *
   * @return array
   *   An array of field definitions of entity fields, keyed by field
   *   name.
   *
   * @see \Drupal\Core\Entity\EntityManager::getFieldDefinitions()
   */
  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);
  }

  /**
   * Clears static and persistent field definition caches.
   */
  public function clearCachedFieldDefinitions() {
    unset($this->entityFieldInfo);
    unset($this->fieldDefinitions);
    $this->cache->deleteTags(array('entity_field_info' => TRUE));
  }

478
}