FieldItemList.php 11.3 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Field\FieldItemList.
6 7
 */

8
namespace Drupal\Core\Field;
9

10
use Drupal\Core\Entity\FieldableEntityInterface;
11
use Drupal\Core\Access\AccessResult;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Language\LanguageInterface;
14
use Drupal\Core\Session\AccountInterface;
15
use Drupal\Core\TypedData\DataDefinitionInterface;
16
use Drupal\Core\TypedData\Plugin\DataType\ItemList;
17
use Drupal\Core\TypedData\TypedDataInterface;
18 19

/**
20
 * Represents an entity field; that is, a list of field item objects.
21
 *
22 23 24 25
 * An entity field is a list of field items, each containing a set of
 * properties. Note that even single-valued entity fields are represented as
 * list of field items, however for easy access to the contained item the entity
 * field delegates __get() and __set() calls directly to the first item.
26
 */
27
class FieldItemList extends ItemList implements FieldItemListInterface {
28 29

  /**
30
   * Numerically indexed array of field items.
31
   *
32
   * @var \Drupal\Core\Field\FieldItemInterface[]
33 34 35
   */
  protected $list = array();

36 37 38 39 40
  /**
   * The langcode of the field values held in the object.
   *
   * @var string
   */
41
  protected $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
42

43 44 45 46 47 48 49
  /**
   * {@inheritdoc}
   */
  protected function createItem($offset = 0, $value = NULL) {
    return \Drupal::service('plugin.manager.field.field_type')->createFieldItem($this, $offset, $value);
  }

50 51 52 53
  /**
   * {@inheritdoc}
   */
  public function getEntity() {
54 55 56
    // The "parent" is the TypedData object for the entity, we need to unwrap
    // the actual entity.
    return $this->getParent()->getValue();
57 58
  }

59 60 61 62 63 64 65 66 67 68 69 70 71 72
  /**
   * {@inheritdoc}
   */
  public function setLangcode($langcode) {
    $this->langcode = $langcode;
  }

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

73 74 75 76
  /**
   * {@inheritdoc}
   */
  public function getFieldDefinition() {
77
    return $this->definition;
78 79
  }

80 81 82 83 84 85 86 87 88 89 90 91 92 93
  /**
   * {@inheritdoc}
   */
  public function getSettings() {
    return $this->definition->getSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function getSetting($setting_name) {
    return $this->definition->getSetting($setting_name);
  }

94
  /**
95
   * {@inheritdoc}
96
   */
97
  public function filterEmptyItems() {
98 99 100
    $this->filter(function ($item) {
      return !$item->isEmpty();
    });
101
    return $this;
102 103
  }

104 105 106 107 108
  /**
   * {@inheritdoc}
   * @todo Revisit the need when all entity types are converted to NG entities.
   */
  public function getValue($include_computed = FALSE) {
109 110 111
    $values = array();
    foreach ($this->list as $delta => $item) {
      $values[$delta] = $item->getValue($include_computed);
112
    }
113
    return $values;
114 115
  }

116
  /**
117
   * {@inheritdoc}
118
   */
119
  public function setValue($values, $notify = TRUE) {
120 121 122 123
    // Support passing in only the value of the first item, either as a litteral
    // (value of the first property) or as an array of properties.
    if (isset($values) && (!is_array($values) || (!empty($values) && !is_numeric(current(array_keys($values)))))) {
      $values = array(0 => $values);
124
    }
125
    parent::setValue($values, $notify);
126 127
  }

128
  /**
129
   * {@inheritdoc}
130 131
   */
  public function __get($property_name) {
132 133 134 135
    // For empty fields, $entity->field->property is NULL.
    if ($item = $this->first()) {
      return $item->__get($property_name);
    }
136 137 138
  }

  /**
139
   * {@inheritdoc}
140 141
   */
  public function __set($property_name, $value) {
142 143 144 145
    // For empty fields, $entity->field->property = $value automatically
    // creates the item before assigning the value.
    $item = $this->first() ?: $this->appendItem();
    $item->__set($property_name, $value);
146 147 148
  }

  /**
149
   * {@inheritdoc}
150 151
   */
  public function __isset($property_name) {
152 153 154 155
    if ($item = $this->first()) {
      return $item->__isset($property_name);
    }
    return FALSE;
156 157 158
  }

  /**
159
   * {@inheritdoc}
160 161
   */
  public function __unset($property_name) {
162 163 164
    if ($item = $this->first()) {
      $item->__unset($property_name);
    }
165 166 167
  }

  /**
168
   * {@inheritdoc}
169
   */
170
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
171
    $access_control_handler = \Drupal::entityManager()->getAccessControlHandler($this->getEntity()->getEntityTypeId());
172
    return $access_control_handler->fieldAccess($operation, $this->getFieldDefinition(), $account, $this, $return_as_object);
173 174 175
  }

  /**
176
   * {@inheritdoc}
177
   */
178
  public function defaultAccess($operation = 'view', AccountInterface $account = NULL) {
179
    // Grant access per default.
180
    return AccessResult::allowed();
181
  }
182

183 184 185 186
  /**
   * {@inheritdoc}
   */
  public function applyDefaultValue($notify = TRUE) {
187 188
    if ($value = $this->getFieldDefinition()->getDefaultValue($this->getEntity())) {
      $this->setValue($value, $notify);
189
    }
190
    else {
191 192 193 194 195 196 197
      // Create one field item and give it a chance to apply its defaults.
      // Remove it if this ended up doing nothing.
      // @todo Having to create an item in case it wants to set a value is
      // absurd. Remove that in https://www.drupal.org/node/2356623.
      $item = $this->first() ?: $this->appendItem();
      $item->applyDefaultValue(FALSE);
      $this->filterEmptyItems();
198
    }
199 200 201
    return $this;
  }

202 203 204 205 206
  /**
   * {@inheritdoc}
   */
  public function preSave() {
    // Filter out empty items.
207
    $this->filterEmptyItems();
208

209
    $this->delegateMethod('preSave');
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
  }

  /**
   * {@inheritdoc}
   */
  public function insert() {
    $this->delegateMethod('insert');
  }

  /**
   * {@inheritdoc}
   */
  public function update() {
    $this->delegateMethod('update');
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {
    $this->delegateMethod('delete');
  }

  /**
   * {@inheritdoc}
   */
  public function deleteRevision() {
    $this->delegateMethod('deleteRevision');
  }

  /**
   * Calls a method on each FieldItem.
   *
   * @param string $method
   *   The name of the method.
   */
  protected function delegateMethod($method) {
247 248
    foreach ($this->list as $item) {
      $item->{$method}();
249 250 251
    }
  }

252 253 254 255 256 257 258 259
  /**
   * {@inheritdoc}
   */
  public function view($display_options = array()) {
    $view_builder = \Drupal::entityManager()->getViewBuilder($this->getEntity()->getEntityTypeId());
    return $view_builder->viewField($this, $display_options);
  }

260 261 262 263 264 265 266 267 268 269 270 271
  /**
   * {@inheritdoc}
   */
   public function generateSampleItems($count = 1) {
    $field_definition = $this->getFieldDefinition();
    $field_type_class = \Drupal::service('plugin.manager.field.field_type')->getPluginClass($field_definition->getType());
    for ($delta = 0; $delta < $count; $delta++) {
      $values[$delta] = $field_type_class::generateSampleValue($field_definition);
    }
    $this->setValue($values);
  }

272 273 274 275 276 277 278 279
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();
    // Check that the number of values doesn't exceed the field cardinality. For
    // form submitted values, this can only happen with 'multiple value'
    // widgets.
280 281
    $cardinality = $this->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
    if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
282 283 284 285 286 287 288 289 290 291 292 293 294 295
      $constraints[] = \Drupal::typedDataManager()
        ->getValidationConstraintManager()
        ->create('Count', array(
          'max' => $cardinality,
          'maxMessage' => t('%name: this field cannot hold more than @count values.', array('%name' => $this->getFieldDefinition()->getLabel(), '@count' => $cardinality)),
        ));
    }

    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
296
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
297
    if (empty($this->getFieldDefinition()->default_value_callback)) {
298 299 300 301 302 303 304 305 306 307 308 309 310
      // Place the input in a separate place in the submitted values tree.
      $widget = $this->defaultValueWidget($form_state);

      $element = array('#parents' => array('default_value_input'));
      $element += $widget->form($this, $element, $form_state);

      return $element;
    }
  }

  /**
   * {@inheritdoc}
   */
311
  public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) {
312 313 314
    // Extract the submitted value, and validate it.
    $widget = $this->defaultValueWidget($form_state);
    $widget->extractFormValues($this, $element, $form_state);
315 316 317
    // Force a non-required field definition.
    // @see self::defaultValueWidget().
    $this->definition->required = FALSE;
318 319
    $violations = $this->validate();

320
    // Assign reported errors to the correct form element.
321
    if (count($violations)) {
322
      $widget->flagErrors($this, $violations, $element, $form_state);
323 324 325 326 327 328
    }
  }

  /**
   * {@inheritdoc}
   */
329
  public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
330 331 332 333 334 335
    // Extract the submitted value, and return it as an array.
    $widget = $this->defaultValueWidget($form_state);
    $widget->extractFormValues($this, $element, $form_state);
    return $this->getValue();
  }

336 337 338
  /**
   * {@inheritdoc}
   */
339
  public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
340 341 342
    return $default_value;
  }

343 344 345
  /**
   * Returns the widget object used in default value form.
   *
346
   * @param \Drupal\Core\Form\FormStateInterface $form_state
347 348 349 350 351
   *   The form state of the (entire) configuration form.
   *
   * @return \Drupal\Core\Field\WidgetInterface
   *   A Widget object.
   */
352
  protected function defaultValueWidget(FormStateInterface $form_state) {
353
    if (!$form_state->has('default_value_widget')) {
354 355 356 357 358 359 360 361 362 363 364 365 366 367
      $entity = $this->getEntity();

      // Force a non-required widget.
      $this->getFieldDefinition()->required = FALSE;
      $this->getFieldDefinition()->description = '';

      // Use the widget currently configured for the 'default' form mode, or
      // fallback to the default widget for the field type.
      $entity_form_display = entity_get_form_display($entity->getEntityTypeId(), $entity->bundle(), 'default');
      $widget = $entity_form_display->getRenderer($this->getFieldDefinition()->getName());
      if (!$widget) {
        $widget = \Drupal::service('plugin.manager.field.widget')->getInstance(array('field_definition' => $this->getFieldDefinition()));
      }

368
      $form_state->set('default_value_widget', $widget);
369 370
    }

371
    return $form_state->get('default_value_widget');
372 373
  }

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
  /**
   * {@inheritdoc}
   */
  public function equals(FieldItemListInterface $list_to_compare) {
    $columns = $this->getFieldDefinition()->getFieldStorageDefinition()->getColumns();
    $count1 = count($this);
    $count2 = count($list_to_compare);
    if ($count1 === 0 && $count2 === 0) {
      // Both are empty we can safely assume that it did not change.
      return TRUE;
    }
    if ($count1 !== $count2) {
      // One of them is empty but not the other one so the value changed.
      return FALSE;
    }
    $value1 = $this->getValue();
    $value2 = $list_to_compare->getValue();
    if ($value1 === $value2) {
      return TRUE;
    }
    // If the values are not equal ensure a consistent order of field item
    // properties and remove properties which will not be saved.
    $callback = function (&$value) use ($columns) {
      if (is_array($value)) {
        $value = array_intersect_key($value, $columns);
        ksort($value);
      }
    };
    array_walk($value1, $callback);
    array_walk($value2, $callback);

405
    return $value1 == $value2;
406 407
  }

408
}