FieldItemList.php 11.9 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\Access\AccessResult;
11
use Drupal\Core\Entity\FieldableEntityInterface;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Language\LanguageInterface;
14
use Drupal\Core\Session\AccountInterface;
15
use Drupal\Core\TypedData\Plugin\DataType\ItemList;
16 17

/**
18
 * Represents an entity field; that is, a list of field item objects.
19
 *
20 21 22 23
 * 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.
24
 */
25
class FieldItemList extends ItemList implements FieldItemListInterface {
26 27

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

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

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

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

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

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

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

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

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

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

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

114
  /**
115
   * {@inheritdoc}
116
   */
117
  public function setValue($values, $notify = TRUE) {
118 119 120 121
    // 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);
122
    }
123
    parent::setValue($values, $notify);
124 125
  }

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

  /**
137
   * {@inheritdoc}
138 139
   */
  public function __set($property_name, $value) {
140 141 142 143
    // 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);
144 145 146
  }

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

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

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

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

181 182 183 184
  /**
   * {@inheritdoc}
   */
  public function applyDefaultValue($notify = TRUE) {
185 186
    if ($value = $this->getFieldDefinition()->getDefaultValue($this->getEntity())) {
      $this->setValue($value, $notify);
187
    }
188
    else {
189 190 191 192 193 194 195
      // 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();
196
    }
197 198 199
    return $this;
  }

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

207
    $this->delegateMethod('preSave');
208 209 210 211 212
  }

  /**
   * {@inheritdoc}
   */
213 214 215
  public function postSave($update) {
    $result = $this->delegateMethod('postSave', $update);
    return (bool) array_filter($result);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  }

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

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

  /**
   * Calls a method on each FieldItem.
   *
235 236
   * Any argument passed will be forwarded to the invoked method.
   *
237
   * @param string $method
238 239 240 241
   *   The name of the method to be invoked.
   *
   * @return array
   *   An array of results keyed by delta.
242 243
   */
  protected function delegateMethod($method) {
244 245 246 247 248 249
    $result = [];
    $args = array_slice(func_get_args(), 1);
    foreach ($this->list as $delta => $item) {
      // call_user_func_array() is way slower than a direct call so we avoid
      // using it if have no parameters.
      $result[$delta] = $args ? call_user_func_array([$item, $method], $args) : $item->{$method}();
250
    }
251
    return $result;
252 253
  }

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

262 263 264 265 266 267 268 269 270 271 272 273
  /**
   * {@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);
  }

274 275 276 277 278 279 280 281
  /**
   * {@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.
282 283
    $cardinality = $this->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
    if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
284 285 286 287 288 289 290 291 292 293 294 295 296 297
      $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}
   */
298
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
299
    if (empty($this->getFieldDefinition()->getDefaultValueCallback())) {
300 301 302 303 304 305 306 307 308 309
      if ($widget = $this->defaultValueWidget($form_state)) {
        // Place the input in a separate place in the submitted values tree.
        $element = array('#parents' => array('default_value_input'));
        $element += $widget->form($this, $element, $form_state);

        return $element;
      }
      else {
        return ['#markup' => $this->t('No widget available for: %type.', ['%type' => $this->getFieldDefinition()->getType()])];
      }
310 311 312 313 314 315
    }
  }

  /**
   * {@inheritdoc}
   */
316
  public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) {
317
    // Extract the submitted value, and validate it.
318 319 320 321 322 323 324 325 326 327 328
    if ($widget = $this->defaultValueWidget($form_state)) {
      $widget->extractFormValues($this, $element, $form_state);
      // Force a non-required field definition.
      // @see self::defaultValueWidget().
      $this->getFieldDefinition()->setRequired(FALSE);
      $violations = $this->validate();

      // Assign reported errors to the correct form element.
      if (count($violations)) {
        $widget->flagErrors($this, $violations, $element, $form_state);
      }
329 330 331 332 333 334
    }
  }

  /**
   * {@inheritdoc}
   */
335
  public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
336
    // Extract the submitted value, and return it as an array.
337 338 339 340
    if ($widget = $this->defaultValueWidget($form_state)) {
      $widget->extractFormValues($this, $element, $form_state);
      return $this->getValue();
    }
341 342
  }

343 344 345
  /**
   * {@inheritdoc}
   */
346
  public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
347 348 349
    return $default_value;
  }

350 351 352
  /**
   * Returns the widget object used in default value form.
   *
353
   * @param \Drupal\Core\Form\FormStateInterface $form_state
354 355
   *   The form state of the (entire) configuration form.
   *
356 357
   * @return \Drupal\Core\Field\WidgetInterface|null
   *   A Widget object or NULL if no widget is available.
358
   */
359
  protected function defaultValueWidget(FormStateInterface $form_state) {
360
    if (!$form_state->has('default_value_widget')) {
361 362 363
      $entity = $this->getEntity();

      // Force a non-required widget.
364 365 366
      $definition = $this->getFieldDefinition();
      $definition->setRequired(FALSE);
      $definition->setDescription('');
367 368 369 370 371 372 373 374 375

      // 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()));
      }

376
      $form_state->set('default_value_widget', $widget);
377 378
    }

379
    return $form_state->get('default_value_widget');
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 405 406 407 408 409 410 411 412
  /**
   * {@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);

413
    return $value1 == $value2;
414 415
  }

416
}