You are here

public function ItemList::set in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/TypedData/Plugin/DataType/ItemList.php \Drupal\Core\TypedData\Plugin\DataType\ItemList::set()

Sets the value of the item at a given position in the list.

Parameters

int $index: The position of the item in the list. Since a List only contains sequential, 0-based indexes, $index has to be:

  • Either the position of an existing item in the list. This updates the

item value.

  • Or the next available position in the sequence of the current list

indexes. This appends a new item with the provided value at the end of the list.

mixed $value: The value of the item to be stored at the specified position.

Return value

$this

Throws

\InvalidArgumentException If the $index is invalid (non-numeric, or pointing to an invalid position in the list).

\Drupal\Core\TypedData\Exception\MissingDataException If the complex data structure is unset and no item can be set.

Overrides ListInterface::set

1 call to ItemList::set()
ItemList::offsetSet in core/lib/Drupal/Core/TypedData/Plugin/DataType/ItemList.php

File

core/lib/Drupal/Core/TypedData/Plugin/DataType/ItemList.php, line 109

Class

ItemList
A generic list class.

Namespace

Drupal\Core\TypedData\Plugin\DataType

Code

public function set($index, $value) {
  if (!is_numeric($index)) {
    throw new \InvalidArgumentException('Unable to set a value with a non-numeric delta in a list.');
  }

  // Ensure indexes stay sequential. We allow assigning an item at an existing
  // index, or at the next index available.
  if ($index < 0 || $index > count($this->list)) {
    throw new \InvalidArgumentException('Unable to set a value to a non-subsequent delta in a list.');
  }

  // Support setting values via typed data objects.
  if ($value instanceof TypedDataInterface) {
    $value = $value
      ->getValue();
  }

  // If needed, create the item at the next position.
  $item = isset($this->list[$index]) ? $this->list[$index] : $this
    ->appendItem();
  $item
    ->setValue($value);
  return $this;
}