FieldInfo.php 18.5 KB
Newer Older
1 2
<?php

3
/**
4
 * @file
5
 * Contains \Drupal\field\FieldInfo.
6 7 8 9
 */

namespace Drupal\field;

10
use Drupal\Core\Cache\Cache;
11
use Drupal\Core\Cache\CacheBackendInterface;
12
use Drupal\Core\Config\ConfigFactory;
13
use Drupal\Core\Field\FieldTypePluginManager;
14
use Drupal\Core\Extension\ModuleHandlerInterface;
15 16
use Drupal\field\FieldInterface;
use Drupal\field\FieldInstanceInterface;
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/**
 * Provides field and instance definitions for the current runtime environment.
 *
 * The preferred way to access definitions is through the getBundleInstances()
 * method, which keeps cache entries per bundle, storing both fields and
 * instances for a given bundle. Fields used in multiple bundles are duplicated
 * in several cache entries, and are merged into a single list in the memory
 * cache. Cache entries are loaded for bundles as a whole, optimizing memory
 * and CPU usage for the most common pattern of iterating over all instances of
 * a bundle rather than accessing a single instance.
 *
 * The getFields() and getInstances() methods, which return all existing field
 * and instance definitions, are kept mainly for backwards compatibility, and
 * should be avoided when possible, since they load and persist in memory a
 * potentially large array of information. In many cases, the lightweight
 * getFieldMap() method should be preferred.
 */
class FieldInfo {

37 38 39 40 41 42 43 44 45 46 47 48 49 50
  /**
   * The cache backend to use.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

  /**
   * Stores a module manager to invoke hooks.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

51 52 53
  /**
   * The field type manager to define field.
   *
54
   * @var \Drupal\Core\Field\FieldTypePluginManager
55 56 57
   */
  protected $fieldTypeManager;

58 59 60 61 62 63 64
  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $config;

65 66 67 68 69 70 71 72 73 74
  /**
   * Lightweight map of fields across entity types and bundles.
   *
   * @var array
   */
  protected $fieldMap;

  /**
   * List of $field structures keyed by ID. Includes deleted fields.
   *
75
   * @var \Drupal\field\FieldInterface[]
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
   */
  protected $fieldsById = array();

  /**
   * Mapping of field names to the ID of the corresponding non-deleted field.
   *
   * @var array
   */
  protected $fieldIdsByName = array();

  /**
   * Whether $fieldsById contains all field definitions or a subset.
   *
   * @var bool
   */
  protected $loadedAllFields = FALSE;

  /**
94
   * Separately tracks requested field names or IDs that do not exist.
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
   *
   * @var array
   */
  protected $unknownFields = array();

  /**
   * Instance definitions by bundle.
   *
   * @var array
   */
  protected $bundleInstances = array();

  /**
   * Whether $bundleInstances contains all instances definitions or a subset.
   *
   * @var bool
   */
  protected $loadedAllInstances = FALSE;

  /**
   * Separately tracks requested bundles that are empty (or do not exist).
   *
   * @var array
   */
  protected $emptyBundles = array();

  /**
   * Extra fields by bundle.
   *
   * @var array
   */
  protected $bundleExtraFields = array();

128 129 130 131 132 133 134 135 136
  /**
   * Constructs this FieldInfo object.
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   The cache backend to use.
   * @param \Drupal\Core\Config\ConfigFactory $config
   *   The configuration factory object to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler class to use for invoking hooks.
137
   * @param \Drupal\Core\Field\FieldTypePluginManager $field_type_manager
138
   *   The 'field type' plugin manager.
139
   */
140
  public function __construct(CacheBackendInterface $cache_backend, ConfigFactory $config, ModuleHandlerInterface $module_handler, FieldTypePluginManager $field_type_manager) {
141 142 143
    $this->cacheBackend = $cache_backend;
    $this->moduleHandler = $module_handler;
    $this->config = $config;
144
    $this->fieldTypeManager = $field_type_manager;
145 146
  }

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  /**
   * Clears the "static" and persistent caches.
   */
  public function flush() {
    $this->fieldMap = NULL;

    $this->fieldsById = array();
    $this->fieldIdsByName = array();
    $this->loadedAllFields = FALSE;
    $this->unknownFields = array();

    $this->bundleInstances = array();
    $this->loadedAllInstances = FALSE;
    $this->emptyBundles = array();

    $this->bundleExtraFields = array();

164
    Cache::deleteTags(array('field_info' => TRUE));
165 166 167 168 169
  }

  /**
   * Collects a lightweight map of fields across bundles.
   *
170
   * @return array
171 172
   *   An array keyed by entity type. Each value is an array which keys are
   *   field names and value is an array with two entries:
173
   *   - type: The field type.
174
   *   - bundles: The bundles in which the field appears.
175 176 177 178 179 180 181 182
   */
  public function getFieldMap() {
    // Read from the "static" cache.
    if ($this->fieldMap !== NULL) {
      return $this->fieldMap;
    }

    // Read from persistent cache.
183
    if ($cached = $this->cacheBackend->get('field_info:field_map')) {
184 185 186 187 188 189 190 191 192 193
      $map = $cached->data;

      // Save in "static" cache.
      $this->fieldMap = $map;

      return $map;
    }

    $map = array();

194
    // Get fields.
195
    foreach (config_get_storage_names_with_prefix('field.field.') as $config_id) {
196
      $field_config = $this->config->get($config_id)->get();
197
      $fields[$field_config['uuid']] = $field_config;
198 199
    }
    // Get field instances.
200
    foreach (config_get_storage_names_with_prefix('field.instance.') as $config_id) {
201
      $instance_config = $this->config->get($config_id)->get();
202 203 204
      $field_uuid = $instance_config['field_uuid'];
      if (isset($fields[$field_uuid])) {
        $field = $fields[$field_uuid];
205 206
        $map[$instance_config['entity_type']][$field['name']]['bundles'][] = $instance_config['bundle'];
        $map[$instance_config['entity_type']][$field['name']]['type'] = $field['type'];
207
      }
208 209 210 211
    }

    // Save in "static" and persistent caches.
    $this->fieldMap = $map;
212
    $this->cacheBackend->set('field_info:field_map', $map, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
213 214 215 216 217

    return $map;
  }

  /**
218
   * Returns all fields, including deleted ones.
219
   *
220 221
   * @return \Drupal\field\FieldInterface[]
   *   An array of field entities, keyed by field ID.
222 223 224 225 226 227 228 229
   */
  public function getFields() {
    // Read from the "static" cache.
    if ($this->loadedAllFields) {
      return $this->fieldsById;
    }

    // Read from persistent cache.
230
    if ($cached = $this->cacheBackend->get('field_info:fields')) {
231 232 233 234
      $this->fieldsById = $cached->data;
    }
    else {
      // Collect and prepare fields.
235
      foreach (entity_load_multiple_by_properties('field_entity', array('include_deleted' => TRUE)) as $field) {
236
        $this->fieldsById[$field->uuid()] = $this->prepareField($field);
237 238 239
      }

      // Store in persistent cache.
240
      $this->cacheBackend->set('field_info:fields', $this->fieldsById, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
241 242 243 244
    }

    // Fill the name/ID map.
    foreach ($this->fieldsById as $field) {
245
      if (!$field->deleted) {
246
        $this->fieldIdsByName[$field->entity_type][$field->getName()] = $field->uuid();
247 248 249 250 251 252 253 254 255
      }
    }

    $this->loadedAllFields = TRUE;

    return $this->fieldsById;
  }

  /**
256
   * Retrieves all non-deleted instances definitions.
257
   *
258
   * @param string $entity_type
259 260
   *   (optional) The entity type.
   *
261
   * @return array
262 263 264 265 266 267 268 269 270
   *   If $entity_type is not set, all instances keyed by entity type and bundle
   *   name. If $entity_type is set, all instances for that entity type, keyed
   *   by bundle name.
   */
  public function getInstances($entity_type = NULL) {
    // If the full list is not present in "static" cache yet.
    if (!$this->loadedAllInstances) {

      // Read from persistent cache.
271
      if ($cached = $this->cacheBackend->get('field_info:instances')) {
272 273 274 275 276 277 278 279 280
        $this->bundleInstances = $cached->data;
      }
      else {
        // Collect and prepare instances.

        // We also need to populate the static field cache, since it will not
        // be set by subsequent getBundleInstances() calls.
        $this->getFields();

281
        foreach (entity_load_multiple('field_instance') as $instance) {
282
          $instance = $this->prepareInstance($instance);
283
          $this->bundleInstances[$instance->entity_type][$instance->bundle][$instance->getName()] = $instance;
284 285 286
        }

        // Store in persistent cache.
287
        $this->cacheBackend->set('field_info:instances', $this->bundleInstances, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
      }

      $this->loadedAllInstances = TRUE;
    }

    if (isset($entity_type)) {
      return isset($this->bundleInstances[$entity_type]) ? $this->bundleInstances[$entity_type] : array();
    }
    else {
      return $this->bundleInstances;
    }
  }

  /**
   * Returns a field definition from a field name.
   *
304
   * This method only retrieves non-deleted fields.
305
   *
306 307 308
   * @param string $entity_type
   *   The entity type.
   * @param string $field_name
309 310
   *   The field name.
   *
311
   * @return \Drupal\field\FieldInterface|null
312 313
   *   The field definition, or NULL if no field was found.
   */
314
  public function getField($entity_type, $field_name) {
315
    // Read from the "static" cache.
316 317
    if (isset($this->fieldIdsByName[$entity_type][$field_name])) {
      $field_id = $this->fieldIdsByName[$entity_type][$field_name];
318 319
      return $this->fieldsById[$field_id];
    }
320
    if (isset($this->unknownFields[$entity_type][$field_name])) {
321 322 323 324 325 326
      return;
    }

    // Do not check the (large) persistent cache, but read the definition.

    // Cache miss: read from definition.
327
    if ($field = entity_load('field_entity', $entity_type . '.' . $field_name)) {
328 329 330
      $field = $this->prepareField($field);

      // Save in the "static" cache.
331 332
      $this->fieldsById[$field->uuid()] = $field;
      $this->fieldIdsByName[$entity_type][$field_name] = $field->uuid();
333 334 335 336

      return $field;
    }
    else {
337
      $this->unknownFields[$entity_type][$field_name] = TRUE;
338 339 340 341
    }
  }

  /**
342
   * Returns a field entity from a field ID.
343
   *
344
   * @param string $field_id
345 346
   *   The field ID.
   *
347 348
   * @return \Drupal\field\FieldInterface|null
   *   The field entity, or NULL if no field was found.
349 350 351 352 353 354 355 356 357 358 359 360 361 362
   */
  public function getFieldById($field_id) {
    // Read from the "static" cache.
    if (isset($this->fieldsById[$field_id])) {
      return $this->fieldsById[$field_id];
    }
    if (isset($this->unknownFields[$field_id])) {
      return;
    }

    // No persistent cache, fields are only persistently cached as part of a
    // bundle.

    // Cache miss: read from definition.
363
    if ($fields = entity_load_multiple_by_properties('field_entity', array('uuid' => $field_id, 'include_deleted' => TRUE))) {
364 365 366 367
      $field = current($fields);
      $field = $this->prepareField($field);

      // Store in the static cache.
368 369
      $this->fieldsById[$field->uuid()] = $field;
      if (!$field->deleted) {
370
        $this->fieldIdsByName[$field->entity_type][$field->getName()] = $field->uuid();
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
      }

      return $field;
    }
    else {
      $this->unknownFields[$field_id] = TRUE;
    }
  }

  /**
   * Retrieves the instances for a bundle.
   *
   * The function also populates the corresponding field definitions in the
   * "static" cache.
   *
386
   * @param string $entity_type
387
   *   The entity type.
388
   * @param string $bundle
389 390
   *   The bundle name.
   *
391 392
   * @return \Drupal\field\FieldInstanceInterface[]
   *   An array of field instance entities, keyed by field name.
393 394 395 396 397 398 399 400 401 402
   */
  public function getBundleInstances($entity_type, $bundle) {
    // Read from the "static" cache.
    if (isset($this->bundleInstances[$entity_type][$bundle])) {
      return $this->bundleInstances[$entity_type][$bundle];
    }
    if (isset($this->emptyBundles[$entity_type][$bundle])) {
      return array();
    }

403 404 405 406 407
    // Read from the persistent cache. We read fields first, since
    // unserializing the cached instance objects tries to access the field
    // definitions.
    if ($cached_fields = $this->cacheBackend->get("field_info:bundle:fields:$entity_type:$bundle")) {
      $fields = $cached_fields->data;
408 409

      // Extract the field definitions and save them in the "static" cache.
410
      foreach ($fields as $field) {
411 412 413
        if (!isset($this->fieldsById[$field->uuid()])) {
          $this->fieldsById[$field->uuid()] = $field;
          if (!$field->deleted) {
414
            $this->fieldIdsByName[$field->entity_type][$field->getName()] = $field->uuid();
415 416 417
          }
        }
      }
418 419 420 421

      // We can now unserialize the instances.
      $cached_instances = $this->cacheBackend->get("field_info:bundle:instances:$entity_type:$bundle");
      $instances = $cached_instances->data;
422

423 424 425
      // Store the instance definitions in the "static" cache'. Empty (or
      // non-existent) bundles are stored separately, so that they do not
      // pollute the global list returned by getInstances().
426 427
      if ($instances) {
        $this->bundleInstances[$entity_type][$bundle] = $instances;
428 429 430 431
      }
      else {
        $this->emptyBundles[$entity_type][$bundle] = TRUE;
      }
432
      return $instances;
433 434 435
    }

    // Cache miss: collect from the definitions.
436
    $field_map = $this->getFieldMap();
437
    $instances = array();
438
    $fields = array();
439

440
    // Do not return anything for unknown entity types.
441
    if (\Drupal::entityManager()->getDefinition($entity_type) && !empty($field_map[$entity_type])) {
442

443
      // Collect names of fields and instances involved in the bundle, using the
444 445
      // field map. The field map is already filtered to non-deleted fields and
      // instances, so those are kept out of the persistent caches.
446
      $config_ids = array();
447 448 449
      foreach ($field_map[$entity_type] as $field_name => $field_data) {
        if (in_array($bundle, $field_data['bundles'])) {
          $config_ids["$entity_type.$field_name"] = "$entity_type.$bundle.$field_name";
450 451
        }
      }
452

453 454
      // Load and prepare the corresponding fields and instances entities.
      if ($config_ids) {
455
        // Place the fields in our global "static".
456
        $loaded_fields = entity_load_multiple('field_entity', array_keys($config_ids));
457
        foreach ($loaded_fields as $field) {
458
          if (!isset($this->fieldsById[$field->uuid()])) {
459 460
            $field = $this->prepareField($field);

461
            $this->fieldsById[$field->uuid()] = $field;
462
            $this->fieldIdsByName[$field->entity_type][$field->getName()] = $field->uuid();
463
          }
464

465
          $fields[] = $this->fieldsById[$field->uuid()];
466
        }
467 468 469 470

        // Then collect the instances.
        $loaded_instances = entity_load_multiple('field_instance', array_values($config_ids));
        foreach ($loaded_instances as $instance) {
471
          $instance = $this->prepareInstance($instance);
472
          $instances[$instance->getName()] = $instance;
473
        }
474 475 476 477 478 479 480 481 482 483 484 485 486
      }
    }

    // Store in the 'static' cache'. Empty (or non-existent) bundles are stored
    // separately, so that they do not pollute the global list returned by
    // getInstances().
    if ($instances) {
      $this->bundleInstances[$entity_type][$bundle] = $instances;
    }
    else {
      $this->emptyBundles[$entity_type][$bundle] = TRUE;
    }

487 488 489 490
    // Store in the persistent cache. Fields and instances are cached in
    // separate entries because they need to be unserialized separately.
    $this->cacheBackend->set("field_info:bundle:fields:$entity_type:$bundle", $fields, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
    $this->cacheBackend->set("field_info:bundle:instances:$entity_type:$bundle", $instances, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
491 492 493 494

    return $instances;
  }

495
  /**
496
   * Returns a field instance.
497 498 499 500 501 502 503 504
   *
   * @param string $entity_type
   *   The entity type for the instance.
   * @param string $bundle
   *   The bundle name for the instance.
   * @param string $field_name
   *   The field name for the instance.
   *
505 506
   * @return \Drupal\field\FieldInstanceInterface|null
   *   The field instance entity, or NULL if it does not exist.
507 508 509 510 511 512 513 514
   */
  function getInstance($entity_type, $bundle, $field_name) {
    $info = $this->getBundleInstances($entity_type, $bundle);
    if (isset($info[$field_name])) {
      return $info[$field_name];
    }
  }

515 516 517
  /**
   * Retrieves the "extra fields" for a bundle.
   *
518
   * @param string $entity_type
519
   *   The entity type.
520
   * @param string $bundle
521 522
   *   The bundle name.
   *
523
   * @return array
524 525 526 527 528 529 530 531 532
   *   The array of extra fields.
   */
  public function getBundleExtraFields($entity_type, $bundle) {
    // Read from the "static" cache.
    if (isset($this->bundleExtraFields[$entity_type][$bundle])) {
      return $this->bundleExtraFields[$entity_type][$bundle];
    }

    // Read from the persistent cache.
533
    if ($cached = $this->cacheBackend->get("field_info:bundle_extra:$entity_type:$bundle")) {
534 535 536 537 538 539 540
      $this->bundleExtraFields[$entity_type][$bundle] = $cached->data;
      return $this->bundleExtraFields[$entity_type][$bundle];
    }

    // Cache miss: read from hook_field_extra_fields(). Note: given the current
    // shape of the hook, we have no other way than collecting extra fields on
    // all bundles.
541
    $extra = $this->moduleHandler->invokeAll('field_extra_fields');
542
    drupal_alter('field_extra_fields', $extra);
543 544
    $info = isset($extra[$entity_type][$bundle]) ? $extra[$entity_type][$bundle] : array();
    $info += array('form' => array(), 'display' => array());
545 546 547

    // Store in the 'static' and persistent caches.
    $this->bundleExtraFields[$entity_type][$bundle] = $info;
548
    $this->cacheBackend->set("field_info:bundle_extra:$entity_type:$bundle", $info, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
549 550 551 552 553

    return $this->bundleExtraFields[$entity_type][$bundle];
  }

  /**
554
   * Prepares a field for the current run-time context.
555
   *
556 557
   * @param \Drupal\field\FieldInterface $field
   *   The field entity to update.
558
   *
559 560
   * @return \Drupal\field\FieldInterface
   *   The field that was prepared.
561
   */
562
  public function prepareField(FieldInterface $field) {
563
    // Make sure all expected field settings are present.
564
    $field->settings += $this->fieldTypeManager->getDefaultSettings($field->getType());
565 566 567 568 569

    return $field;
  }

  /**
570
   * Prepares a field instance for the current run-time context.
571
   *
572
   * @param \Drupal\field\FieldInstanceInterface $instance
573
   *   The field instance entity to prepare.
574
   *
575 576
   * @return \Drupal\field\FieldInstanceInterface
   *   The field instance that was prepared.
577
   */
578
  public function prepareInstance(FieldInstanceInterface $instance) {
579
    // Make sure all expected instance settings are present.
580
    $instance->settings += $this->fieldTypeManager->getDefaultInstanceSettings($instance->getType());
581 582 583 584 585

    return $instance;
  }

}