diff --git a/core/lib/Drupal/Core/Template/Attribute.php b/core/lib/Drupal/Core/Template/Attribute.php index 8aaac3b..0939ed3 100644 --- a/core/lib/Drupal/Core/Template/Attribute.php +++ b/core/lib/Drupal/Core/Template/Attribute.php @@ -240,6 +240,23 @@ public function removeAttribute() { } /** + * Merges the values of another Attributes object with this one. + * + * @param \Drupal\Core\Template\Attribute + * The other Attribute object. + * + * @return $this + */ + public function merge(Attribute $attribute) { + $merged_array = array_merge_recursive($this->toArray(), $attribute->toArray()); + foreach ($merged_array as $attribute => $value) { + $this->setAttribute($attribute, $value); + } + + return $this; + } + + /** * Removes argument values from array of existing CSS classes. * * @param string|array ... diff --git a/core/lib/Drupal/Core/Template/TwigSandboxPolicy.php b/core/lib/Drupal/Core/Template/TwigSandboxPolicy.php index 5423bde..8f90dcf 100644 --- a/core/lib/Drupal/Core/Template/TwigSandboxPolicy.php +++ b/core/lib/Drupal/Core/Template/TwigSandboxPolicy.php @@ -57,6 +57,7 @@ public function __construct() { 'bundle', 'get', '__toString', + 'merge', ]); $this->whitelisted_methods = array_flip($whitelisted_methods); diff --git a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php index 69941a9..8510b89 100644 --- a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php +++ b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php @@ -145,6 +145,38 @@ public function testRemoveAttribute() { } /** + * Tests merging attributes. + * @covers ::merge + */ + public function testMergeAttributes() { + $attributes1 = [ + 'id' => 'koala', + 'class' => array('class1') + ]; + $attribute1 = new Attribute($attributes1); + + $attributes2 = [ + 'name' => 'pinguin', + 'class' => array('class2', 'class3') + ]; + $attribute2 = new Attribute($attributes2); + + // Test merging another Attributes object + $attribute = new Attribute(); + $attribute->merge($attribute1); + $this->assertArrayEquals(['class1'], $attribute['class']->value()); + $this->assertEquals('koala', $attribute['id']->value()); + + // Test merging two Attributes object + $attribute = new Attribute(); + $attribute->merge($attribute1); + $attribute->merge($attribute2); + $this->assertArrayEquals(['class1', 'class2', 'class3'], $attribute['class']->value()); + $this->assertEquals('koala', $attribute['id']->value()); + $this->assertEquals('pinguin', $attribute['name']->value()); + } + + /** * Tests adding class attributes with the AttributeArray helper method. * @covers ::addClass */