EntityDisplay.php 9.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\entity\Plugin\Core\Entity\EntityDisplay.
 */

namespace Drupal\entity\Plugin\Core\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
11
use Drupal\Core\Entity\Annotation\EntityType;
12 13 14 15 16 17
use Drupal\Core\Annotation\Translation;

/**
 * Configuration entity that contains display options for all components of a
 * rendered entity in a given view mode..
 *
18
 * @EntityType(
19 20 21
 *   id = "entity_display",
 *   label = @Translation("Entity display"),
 *   module = "entity",
22 23 24
 *   controllers = {
 *     "storage" = "Drupal\Core\Config\Entity\ConfigStorageController"
 *   },
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 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 91 92 93 94 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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 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 336 337 338 339 340 341 342 343 344 345 346 347
 *   config_prefix = "entity.display",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid"
 *   }
 * )
 */
class EntityDisplay extends ConfigEntityBase {

  /**
   * Unique ID for the config entity.
   *
   * @var string
   */
  public $id;

  /**
   * Unique UUID for the config entity.
   *
   * @var string
   */
  public $uuid;

  /**
   * Entity type to be displayed.
   *
   * @var string
   */
  public $targetEntityType;

  /**
   * Bundle to be displayed.
   *
   * @var string
   */
  public $bundle;

  /**
   * View mode to be displayed.
   *
   * @var string
   */
  public $viewMode;

  /**
   * List of component display options, keyed by component name.
   *
   * @var array
   */
  protected $content = array();

  /**
   * The original view mode that was requested (case of view modes being
   * configured to fall back to the 'default' display).
   *
   * @var string
   */
  public $originalViewMode;

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

  /**
   * Overrides \Drupal\Core\Config\Entity\ConfigEntityBase::__construct().
   */
  public function __construct(array $values, $entity_type) {
    // @todo See http://drupal.org/node/1825044#comment-6847792: contact.module
    // currently produces invalid entities with a NULL bundle in some cases.
    // Add the validity checks back when http://drupal.org/node/1856556 is
    // fixed.
    // if (!isset($values['targetEntityType']) || !isset($values['bundle']) || !isset($values['viewMode'])) {
    //   throw new \InvalidArgumentException('Missing required properties for an EntiyDisplay entity.');
    // }
    parent::__construct($values, $entity_type);

    $this->originalViewMode = $this->viewMode;
  }

  /**
   * Overrides \Drupal\Core\Entity\Entity::id().
   */
  public function id() {
    return $this->targetEntityType . '.' . $this->bundle . '.' . $this->viewMode;
  }

  /**
   * Overrides \Drupal\config\ConfigEntityBase::save().
   */
  public function save() {
    // Build an ID if none is set.
    if (empty($this->id)) {
      $this->id = $this->id();
    }
    return parent::save();
  }

  /**
   * Overrides \Drupal\config\ConfigEntityBase::getExportProperties();
   */
  public function getExportProperties() {
    $names = array(
      'id',
      'uuid',
      'targetEntityType',
      'bundle',
      'viewMode',
      'content',
    );
    $properties = array();
    foreach ($names as $name) {
      $properties[$name] = $this->get($name);
    }
    return $properties;
  }

  /**
   * Creates a duplicate of the EntityDisplay object on a different view mode.
   *
   * The new object necessarily has the same $targetEntityType and $bundle
   * properties than the original one.
   *
   * @param $view_mode
   *   The view mode for the new object.
   *
   * @return \Drupal\entity\Plugin\Core\Entity\EntityDisplay
   *   The new object.
   */
  public function createCopy($view_mode) {
    $display = $this->createDuplicate();
    $display->viewMode = $display->originalViewMode = $view_mode;
    return $display;
  }

  /**
   * Gets the display options for all components.
   *
   * @return array
   *   The array of display options, keyed by component name.
   */
  public function getComponents() {
    $result = array();
    foreach ($this->content as $name => $options) {
      if (!isset($options['visible']) || $options['visible'] === TRUE) {
        unset($options['visible']);
        $result[$name] = $options;
      }
    }
    return $result;
  }

  /**
   * Gets the display options set for a component.
   *
   * @param string $name
   *   The name of the component.
   *
   * @return array|null
   *   The display options for the component, or NULL if the component is not
   *   displayed.
   */
  public function getComponent($name) {
    // We always store 'extra fields', whether they are visible or hidden.
    $extra_fields = field_info_extra_fields($this->targetEntityType, $this->bundle, 'display');
    if (isset($extra_fields[$name])) {
      // If we have explicit settings, return an array or NULL depending on
      // visibility.
      if (isset($this->content[$name])) {
        if ($this->content[$name]['visible']) {
          return array(
            'weight' => $this->content[$name]['weight'],
          );
        }
        else {
          return NULL;
        }
      }

      // If no explicit settings for the extra field, look at the default
      // visibility in its definition.
      $definition = $extra_fields[$name];
      if (!isset($definition['visible']) || $definition['visible'] == TRUE) {
        return array(
          'weight' => $definition['weight']
        );
      }
      else {
        return NULL;
      }
    }

    if (isset($this->content[$name])) {
      return $this->content[$name];
    }
  }

  /**
   * Sets the display options for a component.
   *
   * @param string $name
   *   The name of the component.
   * @param array $options
   *   The display options.
   *
   * @return \Drupal\entity\Plugin\Core\Entity\EntityDisplay
   *   The EntityDisplay object.
   */
  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;
    }

    if ($instance = field_info_instance($this->targetEntityType, $name, $this->bundle)) {
      $field = field_info_field($instance['field_name']);
      $options = drupal_container()->get('plugin.manager.field.formatter')->prepareConfiguration($field['type'], $options);

      // Clear the persisted formatter, if any.
      unset($this->formatters[$name]);
    }

    // We always store 'extra fields', whether they are visible or hidden.
    $extra_fields = field_info_extra_fields($this->targetEntityType, $this->bundle, 'display');
    if (isset($extra_fields[$name])) {
      $options['visible'] = TRUE;
    }

    $this->content[$name] = $options;

    return $this;
  }

  /**
   * Sets a component to be hidden.
   *
   * @param string $name
   *   The name of the component.
   *
   * @return \Drupal\entity\Plugin\Core\Entity\EntityDisplay
   *   The EntityDisplay object.
   */
  public function removeComponent($name) {
    $extra_fields = field_info_extra_fields($this->targetEntityType, $this->bundle, 'display');
    if (isset($extra_fields[$name])) {
      // 'Extra fields' are exposed in hooks and can appear at any given time.
      // Therefore we store extra fields that are explicitly being hidden, so
      // that we can differenciate with those that are simply not configured
      // yet.
      $this->content[$name] = array(
        'visible' => FALSE,
      );
    }
    else {
      unset($this->content[$name]);
      unset($this->formatters[$name]);
    }

    return $this;
  }

  /**
   * Returns the highest weight of the components in the display.
   *
   * @return int|null
   *   The highest weight of the components in the display, or NULL if the
   *   display is empty.
   */
  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.
    $weights = array_merge($weights, module_invoke_all('field_info_max_weight', $this->targetEntityType, $this->bundle, $this->viewMode));

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

  /**
   * Returns the Formatter plugin for a field.
   *
   * @param string $field_name
   *   The field name.
   *
   * @return \Drupal\field\Plugin\Type\Formatter\FormatterInterface
   *   If the field is not hidden, the Formatter plugin to use for rendering
   *   it.
   */
  public function getFormatter($field_name) {
    if (isset($this->formatters[$field_name])) {
      return $this->formatters[$field_name];
    }

    // Instantiate the formatter object from the stored display properties.
    if ($configuration = $this->getComponent($field_name)) {
      $instance = field_info_instance($this->targetEntityType, $field_name, $this->bundle);
      $formatter = drupal_container()->get('plugin.manager.field.formatter')->getInstance(array(
        'instance' => $instance,
        'view_mode' => $this->originalViewMode,
        // No need to prepare, defaults have been merged in setComponent().
        'prepare' => FALSE,
        'configuration' => $configuration
      ));
    }
    else {
      $formatter = NULL;
    }

    // Persist the formatter object.
    $this->formatters[$field_name] = $formatter;
    return $formatter;
  }

}