You are here

protected static function TwigExtension::addOrSetFilter in Components! 8.2

Same name and namespace in other branches
  1. 3.x src/Template/TwigExtension.php \Drupal\components\Template\TwigExtension::addOrSetFilter()

Helper function for the set/add filters.

Parameters

array|iterable|\Traversable $element: The parent renderable array to merge into.

string $at: The dotted-path to the deeply nested element to replace.

mixed $value: The value to set.

bool $is_add_filter: Which filter is being called.

Return value

array The merged renderable array.

2 calls to TwigExtension::addOrSetFilter()
TwigExtension::addFilter in src/Template/TwigExtension.php
Adds a deeply-nested property on an array.
TwigExtension::setFilter in src/Template/TwigExtension.php
Sets a deeply-nested property on an array.

File

src/Template/TwigExtension.php, line 259

Class

TwigExtension
A class providing components' Twig extensions.

Namespace

Drupal\components\Template

Code

protected static function addOrSetFilter($element, string $at, $value, $is_add_filter = FALSE) {
  if ($element instanceof \ArrayAccess) {
    $filtered_element = clone $element;
  }
  else {
    $filtered_element = $element;
  }

  // Convert the dotted path into an array of keys.
  $path = explode('.', $at);
  $last_path = array_pop($path);

  // Traverse the element down the path, creating arrays as needed.
  $child_element =& $filtered_element;
  foreach ($path as $child_path) {
    if (!isset($child_element[$child_path])) {
      $child_element[$child_path] = [];
    }
    $child_element =& $child_element[$child_path];
  }

  // If this is the add() filter and if the targeted child element is an
  // array, add the value to it.
  if ($is_add_filter && isset($child_element[$last_path]) && is_array($child_element[$last_path])) {
    if (is_array($value)) {
      $child_element[$last_path] = array_merge($child_element[$last_path], $value);
    }
    else {
      $child_element[$last_path][] = $value;
    }
  }
  else {

    // Otherwise, replace the target element with the given value.
    $child_element[$last_path] = $value;
  }
  return $filtered_element;
}