From 2936a16ac5b64fa6f540d06b0c9c5e8ac0767a67 Mon Sep 17 00:00:00 2001 From: nod_ <nod_@598310.no-reply.drupal.org> Date: Fri, 14 Mar 2025 12:00:11 +0100 Subject: [PATCH] Issue #3334045 by yash.rode, joachim, smustgrave, quietone: Drupal\Core\Template\Attribute doesn't support adding attributes with array syntax if attribute name not already initialised --- core/lib/Drupal/Core/Template/Attribute.php | 7 +++++++ core/tests/Drupal/Tests/Core/Template/AttributeTest.php | 8 ++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/core/lib/Drupal/Core/Template/Attribute.php b/core/lib/Drupal/Core/Template/Attribute.php index 5d68cee9e37d..6e7f5da51473 100644 --- a/core/lib/Drupal/Core/Template/Attribute.php +++ b/core/lib/Drupal/Core/Template/Attribute.php @@ -95,6 +95,13 @@ public function offsetGet($name) { if (isset($this->storage[$name])) { return $this->storage[$name]; } + // The 'class' array key is expected to be itself an array, and therefore + // can be accessed using array append syntax before it has been initialized. + if ($name === 'class') { + // Initialize the class attribute as an empty array if not set. + $this->offsetSet('class', []); + return $this->storage['class']; + } } /** diff --git a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php index f76bc92c7576..46ac4daf36df 100644 --- a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php +++ b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php @@ -148,12 +148,16 @@ public function testRemoveAttribute(): void { * @covers ::addClass */ public function testAddClasses(): void { - // Add empty Attribute object with no classes. + // Add a class with the array syntax without first initializing the 'class' + // attribute. $attribute = new Attribute(); + $attribute['class'][] = 'test-class'; + $this->assertEquals(new AttributeArray('class', ['test-class']), $attribute['class']); + $attribute = new Attribute(); // Add no class on empty attribute. $attribute->addClass(); - $this->assertEmpty($attribute['class']); + $this->assertEmpty($attribute['class']->value()); // Test various permutations of adding values to empty Attribute objects. foreach ([NULL, FALSE, '', []] as $value) { -- GitLab