EntityDisplayBase.php 13.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Entity\EntityDisplayBase.
6 7
 */

8
namespace Drupal\Core\Entity;
9 10

use Drupal\Core\Config\Entity\ConfigEntityBase;
11
use Drupal\Core\Field\FieldDefinitionInterface;
12
use Drupal\Core\Entity\Display\EntityDisplayInterface;
13 14
use Drupal\field\Entity\FieldConfig;
use Drupal\field\FieldConfigInterface;
15
use Drupal\Component\Utility\String;
16 17

/**
18
 * Provides a common base class for entity view and form displays.
19
 */
20
abstract class EntityDisplayBase extends ConfigEntityBase implements EntityDisplayInterface {
21

22 23 24 25 26 27 28 29 30
  /**
   * The 'mode' for runtime EntityDisplay objects used to render entities with
   * arbitrary display options rather than a configured view mode or form mode.
   *
   * @todo Prevent creation of a mode with this ID
   *   https://www.drupal.org/node/2410727
   */
  const CUSTOM_MODE = '_custom';

31 32 33 34 35
  /**
   * Unique ID for the config entity.
   *
   * @var string
   */
36
  protected $id;
37 38 39 40 41 42

  /**
   * Entity type to be displayed.
   *
   * @var string
   */
43
  protected $targetEntityType;
44 45 46 47 48 49

  /**
   * Bundle to be displayed.
   *
   * @var string
   */
50
  protected $bundle;
51

52
  /**
53
   * A list of field definitions eligible for configuration in this display.
54
   *
55
   * @var \Drupal\Core\Field\FieldDefinitionInterface[]
56
   */
57
  protected $fieldDefinitions;
58

59 60 61 62 63
  /**
   * View or form mode to be displayed.
   *
   * @var string
   */
64
  protected $mode = self::CUSTOM_MODE;
65

66 67 68 69 70 71
  /**
   * Whether this display is enabled or not. If the entity (form) display
   * is disabled, we'll fall back to the 'default' display.
   *
   * @var boolean
   */
72
  protected $status;
73

74 75 76 77 78 79 80
  /**
   * List of component display options, keyed by component name.
   *
   * @var array
   */
  protected $content = array();

81 82 83 84 85 86 87
  /**
   * List of components that are set to be hidden.
   *
   * @var array
   */
  protected $hidden = array();

88 89 90 91 92 93
  /**
   * The original view or form mode that was requested (case of view/form modes
   * being configured to fall back to the 'default' display).
   *
   * @var string
   */
94
  protected $originalMode;
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

  /**
   * The plugin objects used for this display, keyed by field name.
   *
   * @var array
   */
  protected $plugins = array();

  /**
   * Context in which this entity will be used (e.g. 'display', 'form').
   *
   * @var string
   */
  protected $displayContext;

  /**
   * The plugin manager used by this entity type.
   *
   * @var \Drupal\Component\Plugin\PluginManagerBase
   */
  protected $pluginManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $values, $entity_type) {
121
    if (!isset($values['targetEntityType']) || !isset($values['bundle'])) {
122 123 124
      throw new \InvalidArgumentException('Missing required properties for an EntityDisplay entity.');
    }

125
    if (!$this->entityManager()->getDefinition($values['targetEntityType'])->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
126
      throw new \InvalidArgumentException('EntityDisplay entities can only handle fieldable entity types.');
127
    }
128 129 130 131 132 133 134 135 136 137 138 139

    // A plugin manager and a context type needs to be set by extending classes.
    if (!isset($this->pluginManager)) {
      throw new \RuntimeException('Missing plugin manager.');
    }
    if (!isset($this->displayContext)) {
      throw new \RuntimeException('Missing display context type.');
    }

    parent::__construct($values, $entity_type);

    $this->originalMode = $this->mode;
140 141

    $this->init();
142 143
  }

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  /**
   * Initializes the display.
   *
   * This fills in default options for components:
   * - that are not explicitly known as either "visible" or "hidden" in the
   *   display,
   * - or that are not supposed to be configurable.
   */
  protected function init() {
    // Only populate defaults for "official" view modes and form modes.
    if ($this->mode !== static::CUSTOM_MODE) {
      // Fill in defaults for extra fields.
      $context = $this->displayContext == 'view' ? 'display' : $this->displayContext;
      $extra_fields = \Drupal::entityManager()->getExtraFields($this->targetEntityType, $this->bundle);
      $extra_fields = isset($extra_fields[$context]) ? $extra_fields[$context] : array();
      foreach ($extra_fields as $name => $definition) {
        if (!isset($this->content[$name]) && !isset($this->hidden[$name])) {
          // Extra fields are visible by default unless they explicitly say so.
          if (!isset($definition['visible']) || $definition['visible'] == TRUE) {
            $this->content[$name] = array(
              'weight' => $definition['weight']
            );
          }
          else {
            $this->hidden[$name] = TRUE;
          }
        }
      }

      // Fill in defaults for fields.
      $fields = $this->getFieldDefinitions();
      foreach ($fields as $name => $definition) {
        if (!$definition->isDisplayConfigurable($this->displayContext) || (!isset($this->content[$name]) && !isset($this->hidden[$name]))) {
          $options = $definition->getDisplayOptions($this->displayContext);

          if (!empty($options['type']) && $options['type'] == 'hidden') {
            $this->hidden[$name] = TRUE;
          }
          elseif ($options) {
            $this->content[$name] = $this->pluginManager->prepareConfiguration($definition->getType(), $options);
          }
          // Note: (base) fields that do not specify display options are not
          // tracked in the display at all, in order to avoid cluttering the
          // configuration that gets saved back.
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetEntityTypeId() {
    return $this->targetEntityType;
  }

  /**
   * {@inheritdoc}
   */
  public function getMode() {
    return $this->get('mode');
  }

  /**
   * {@inheritdoc}
   */
  public function getOriginalMode() {
    return $this->get('originalMode');
  }

  /**
   * {@inheritdoc}
   */
  public function getTargetBundle() {
    return $this->bundle;
  }

  /**
   * {@inheritdoc}
   */
  public function setTargetBundle($bundle) {
    $this->set('bundle', $bundle);
    return $this;
  }

229 230 231 232 233 234 235 236 237
  /**
   * {@inheritdoc}
   */
  public function id() {
    return $this->targetEntityType . '.' . $this->bundle . '.' . $this->mode;
  }

  /**
   * {@inheritdoc}
238
   */
239
  public function preSave(EntityStorageInterface $storage, $update = TRUE) {
240 241
    // Sort elements by weight before saving.
    uasort($this->content, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
242
    parent::preSave($storage, $update);
243 244 245 246 247 248 249
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
250
    $target_entity_type = $this->entityManager()->getDefinition($this->targetEntityType);
251 252 253 254 255

    $bundle_entity_type_id = $target_entity_type->getBundleEntityType();
    if ($bundle_entity_type_id != 'bundle') {
      // If the target entity type uses entities to manage its bundles then
      // depend on the bundle entity.
256
      if (!$bundle_entity = $this->entityManager()->getStorage($bundle_entity_type_id)->load($this->bundle)) {
257 258
        throw new \LogicException(String::format('Missing bundle entity, entity type %type, entity id %bundle.', array('%type' => $bundle_entity_type_id, '%bundle' => $this->bundle)));
      }
259
      $this->addDependency('config', $bundle_entity->getConfigDependencyName());
260
    }
261 262 263 264
    else {
      // Depend on the provider of the entity type.
      $this->addDependency('module', $target_entity_type->getProvider());
    }
265 266 267
    // Create dependencies on both hidden and visible fields.
    $fields = $this->content + $this->hidden;
    foreach ($fields as $field_name => $component) {
268 269
      $field = FieldConfig::loadByName($this->targetEntityType, $this->bundle, $field_name);
      if ($field) {
270
        $this->addDependency('config', $field->getConfigDependencyName());
271 272 273 274
      }
    }
    // Depend on configured modes.
    if ($this->mode != 'default') {
275
      $mode_entity = $this->entityManager()->getStorage('entity_' . $this->displayContext . '_mode')->load($target_entity_type->id() . '.' . $this->mode);
276
      $this->addDependency('config', $mode_entity->getConfigDependencyName());
277 278
    }
    return $this->dependencies;
279
  }
280 281 282

  /**
   * {@inheritdoc}
283
   */
284
  public function toArray() {
285
    $properties = parent::toArray();
286 287 288 289 290 291 292 293 294
    // Do not store options for fields whose display is not set to be
    // configurable.
    foreach ($this->getFieldDefinitions() as $field_name => $definition) {
      if (!$definition->isDisplayConfigurable($this->displayContext)) {
        unset($properties['content'][$field_name]);
        unset($properties['hidden'][$field_name]);
      }
    }

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function createCopy($mode) {
    $display = $this->createDuplicate();
    $display->mode = $display->originalMode = $mode;
    return $display;
  }

  /**
   * {@inheritdoc}
   */
  public function getComponents() {
311
    return $this->content;
312 313 314 315 316 317
  }

  /**
   * {@inheritdoc}
   */
  public function getComponent($name) {
318
    return isset($this->content[$name]) ? $this->content[$name] : NULL;
319 320 321 322 323 324 325 326 327 328 329
  }

  /**
   * {@inheritdoc}
   */
  public function setComponent($name, array $options = array()) {
    // If no weight specified, make sure the field sinks at the bottom.
    if (!isset($options['weight'])) {
      $max = $this->getHighestWeight();
      $options['weight'] = isset($max) ? $max + 1 : 0;
    }
330 331 332

    // For a field, fill in default options.
    if ($field_definition = $this->getFieldDefinition($name)) {
333
      $options = $this->pluginManager->prepareConfiguration($field_definition->getType(), $options);
334 335
    }

336 337 338
    // Ensure we always have an empty settings and array.
    $options += ['settings' => [], 'third_party_settings' => []];

339
    $this->content[$name] = $options;
340 341
    unset($this->hidden[$name]);
    unset($this->plugins[$name]);
342 343 344 345 346 347 348 349

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function removeComponent($name) {
350 351
    $this->hidden[$name] = TRUE;
    unset($this->content[$name]);
352 353
    unset($this->plugins[$name]);

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getHighestWeight() {
    $weights = array();

    // Collect weights for the components in the display.
    foreach ($this->content as $options) {
      if (isset($options['weight'])) {
        $weights[] = $options['weight'];
      }
    }

    // Let other modules feedback about their own additions.
371
    $weights = array_merge($weights, \Drupal::moduleHandler()->invokeAll('field_info_max_weight', array($this->targetEntityType, $this->bundle, $this->displayContext, $this->mode)));
372 373 374 375

    return $weights ? max($weights) : NULL;
  }

376 377 378 379
  /**
   * Returns the field definition of a field.
   */
  protected function getFieldDefinition($field_name) {
380 381 382 383 384 385 386 387 388
    $definitions = $this->getFieldDefinitions();
    return isset($definitions[$field_name]) ? $definitions[$field_name] : NULL;
  }

  /**
   * Returns the definitions of the fields that are candidate for display.
   */
  protected function getFieldDefinitions() {
    if (!isset($this->fieldDefinitions)) {
389
      $definitions = \Drupal::entityManager()->getFieldDefinitions($this->targetEntityType, $this->bundle);
390 391 392 393 394 395
      // For "official" view modes and form modes, ignore fields whose
      // definition states they should not be displayed.
      if ($this->mode !== static::CUSTOM_MODE) {
        $definitions = array_filter($definitions, array($this, 'fieldHasDisplayOptions'));
      }
      $this->fieldDefinitions = $definitions;
396
    }
397 398

    return $this->fieldDefinitions;
399
  }
400

401 402 403 404
  /**
   * Determines if a field has options for a given display.
   *
   * @param FieldDefinitionInterface $definition
405
   *   A field definition.
406 407 408 409 410 411 412 413
   * @return array|null
   */
  private function fieldHasDisplayOptions(FieldDefinitionInterface $definition) {
    // The display only cares about fields that specify display options.
    // Discard base fields that are not rendered through formatters / widgets.
    return $definition->getDisplayOptions($this->displayContext);
  }

414 415 416 417
  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {
418
    $changed = parent::onDependencyRemoval($dependencies);
419
    foreach ($dependencies['config'] as $entity) {
420
      if ($entity instanceof FieldConfigInterface) {
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        // Remove components for fields that are being deleted.
        $this->removeComponent($entity->getName());
        unset($this->hidden[$entity->getName()]);
        $changed = TRUE;
      }
    }
    foreach ($this->getComponents() as $name => $component) {
      if (isset($component['type']) && $definition = $this->pluginManager->getDefinition($component['type'], FALSE)) {
        if (in_array($definition['provider'], $dependencies['module'])) {
          // Revert to the defaults if the plugin that supplies the widget or
          // formatter depends on a module that is being uninstalled.
          $this->setComponent($name);
          $changed = TRUE;
        }
      }
    }
437
    return $changed;
438 439
  }

440 441 442 443 444 445
  /**
   * {@inheritdoc}
   */
  public function __sleep() {
    // Only store the definition, not external objects or derived data.
    $keys = array_keys($this->toArray());
446
    // In addition, we need to keep the entity type and the "is new" status.
447
    $keys[] = 'entityTypeId';
448
    $keys[] = 'enforceIsNew';
449 450 451 452 453
    // Keep track of the serialized keys, to avoid calling toArray() again in
    // __wakeup(). Because of the way __sleep() works, the data has to be
    // present in the object to be included in the serialized values.
    $keys[] = '_serializedKeys';
    $this->_serializedKeys = $keys;
454 455 456 457 458 459 460
    return $keys;
  }

  /**
   * {@inheritdoc}
   */
  public function __wakeup() {
461
    $is_new = $this->isNew();
462 463 464 465 466 467 468
    // Determine what were the properties from toArray() that were saved in
    // __sleep().
    $keys = $this->_serializedKeys;
    unset($this->_serializedKeys);
    $values = array_intersect_key(get_object_vars($this), array_flip($keys));
    // Run those values through the __construct(), as if they came from a
    // regular entity load.
469
    $this->__construct($values, $this->entityTypeId);
470
    $this->enforceIsNew($is_new);
471 472
  }

473
}