function AttributeHelper::mergeCollections

Same name in other branches
  1. 9 core/lib/Drupal/Core/Template/AttributeHelper.php \Drupal\Core\Template\AttributeHelper::mergeCollections()
  2. 8.9.x core/lib/Drupal/Core/Template/AttributeHelper.php \Drupal\Core\Template\AttributeHelper::mergeCollections()
  3. 11.x core/lib/Drupal/Core/Template/AttributeHelper.php \Drupal\Core\Template\AttributeHelper::mergeCollections()

Merges two attribute collections.

Parameters

\Drupal\Core\Template\Attribute|array $a: First Attribute object or array to merge. The returned value type will be the same as the type of this argument.

\Drupal\Core\Template\Attribute|array $b: Second Attribute object or array to merge.

Return value

\Drupal\Core\Template\Attribute|array The merged attributes, as an Attribute object or an array.

Throws

\InvalidArgumentException If at least one collection argument is neither an Attribute object nor an array.

5 calls to AttributeHelper::mergeCollections()
AttributeHelperTest::testMergeCollections in core/tests/Drupal/Tests/Core/Template/AttributeHelperTest.php
@covers ::mergeCollections @dataProvider providerTestMergeCollections
AttributeHelperTest::testMergeCollectionsArgumentException in core/tests/Drupal/Tests/Core/Template/AttributeHelperTest.php
@covers ::mergeCollections
template_preprocess in core/includes/theme.inc
Adds a default set of helper variables for preprocessors and templates.
template_preprocess_field in core/includes/theme.inc
Prepares variables for field templates.
TwigExtension::setAttribute in core/lib/Drupal/Core/Template/TwigExtension.php
Sets an attribute on a given element.

File

core/lib/Drupal/Core/Template/AttributeHelper.php, line 60

Class

AttributeHelper
Helper class to deal with mixed array and Attribute operations.

Namespace

Drupal\Core\Template

Code

public static function mergeCollections($a, $b) {
    if (!($a instanceof Attribute || is_array($a)) || !($b instanceof Attribute || is_array($b))) {
        throw new \InvalidArgumentException('Invalid collection argument');
    }
    // If both collections are arrays, just merge them.
    if (is_array($a) && is_array($b)) {
        return NestedArray::mergeDeep($a, $b);
    }
    // If at least one collections is an Attribute object, merge through
    // Attribute::merge.
    $merge_a = $a instanceof Attribute ? $a : new Attribute($a);
    $merge_b = $b instanceof Attribute ? $b : new Attribute($b);
    $merge_a->merge($merge_b);
    return $a instanceof Attribute ? $merge_a : $merge_a->toArray();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.