diff --git a/core/lib/Drupal/Core/Template/Attribute.php b/core/lib/Drupal/Core/Template/Attribute.php index 7ea9b4c..abd889a 100644 --- a/core/lib/Drupal/Core/Template/Attribute.php +++ b/core/lib/Drupal/Core/Template/Attribute.php @@ -143,7 +143,12 @@ public function addClass() { // Merge the values passed in from the classes array. // The argument is cast to an array to support comma separated single // values or one or more array arguments. - $classes = array_merge($classes, (array) $arg); + // We also filter out any empty values from the array. + $classes = array_filter(array_merge($classes, (array) $arg)); + } + // If there are no classes to add, return early. + if (empty($classes)) { + return $this; } // Merge if there are values, just add them otherwise. diff --git a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php index 9f2cb50..a5cad7b 100644 --- a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php +++ b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php @@ -69,6 +69,25 @@ public function testAddClasses() { $attribute->addClass(); $this->assertEmpty($attribute['class']); + // Test various permutations of adding values to empty Attribute objects. + foreach (array(NULL, FALSE, '', []) as $value) { + // Single value. + $attribute->addClass($value); + $this->assertEmpty($attribute['class']); + + // Multiple values. + $attribute->addClass($value, $value); + $this->assertEmpty($attribute['class']); + + // Single value in array. + $attribute->addClass([$value]); + $this->assertEmpty($attribute['class']); + + // Single value in arrays. + $attribute->addClass([$value], [$value]); + $this->assertEmpty($attribute['class']); + } + // Add one class on empty attribute. $attribute->addClass('banana'); $this->assertArrayEquals(array('banana'), $attribute['class']->value());