From 19ab1c981c1e39e15be5a4b9f7b2c8ffa4ab596d Mon Sep 17 00:00:00 2001 From: Lauri Eskola <lauri.eskola@acquia.com> Date: Fri, 24 Nov 2023 17:49:52 +0200 Subject: [PATCH] Issue #3403331 by pdureau, Utkarsh_33: Prevent TypeError when using create_attribute Twig function --- core/lib/Drupal/Core/Template/TwigExtension.php | 13 ++++++++----- .../Tests/Core/Template/TwigExtensionTest.php | 4 +++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/core/lib/Drupal/Core/Template/TwigExtension.php b/core/lib/Drupal/Core/Template/TwigExtension.php index 60c0ce0ddf4c..9200d0254177 100644 --- a/core/lib/Drupal/Core/Template/TwigExtension.php +++ b/core/lib/Drupal/Core/Template/TwigExtension.php @@ -606,15 +606,18 @@ public function safeJoin(Environment $env, $value, $glue = '') { /** * Creates an Attribute object. * - * @param array $attributes - * (optional) An associative array of key-value pairs to be converted to - * HTML attributes. + * @param Attribute|array $attributes + * (optional) An existing attribute object or an associative array of + * key-value pairs to be converted to HTML attributes. * * @return \Drupal\Core\Template\Attribute * An attributes object that has the given attributes. */ - public function createAttribute(array $attributes = []) { - return new Attribute($attributes); + public function createAttribute(Attribute|array $attributes = []) { + if (\is_array($attributes)) { + return new Attribute($attributes); + } + return $attributes; } /** diff --git a/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php b/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php index 21b1ffe7bba3..6acf1ceabb95 100644 --- a/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php +++ b/core/tests/Drupal/Tests/Core/Template/TwigExtensionTest.php @@ -10,6 +10,7 @@ use Drupal\Core\Render\Markup; use Drupal\Core\Render\RenderableInterface; use Drupal\Core\StringTranslation\TranslatableMarkup; +use Drupal\Core\Template\Attribute; use Drupal\Core\Template\Loader\StringLoader; use Drupal\Core\Template\TwigEnvironment; use Drupal\Core\Template\TwigExtension; @@ -404,9 +405,10 @@ public function testCreateAttribute() { ['class' => ['kittens'], 'data-toggle' => 'modal', 'data-lang' => 'es'], ['id' => 'puppies', 'data-value' => 'foo', 'data-lang' => 'en'], [], + new Attribute(), ]; $result = $twig->render($name, ['iterations' => $iterations]); - $expected = '<div class="kittens" data-toggle="modal" data-lang="es"></div><div id="puppies" data-value="foo" data-lang="en"></div><div></div>'; + $expected = '<div class="kittens" data-toggle="modal" data-lang="es"></div><div id="puppies" data-value="foo" data-lang="en"></div><div></div><div></div>'; $this->assertEquals($expected, $result); // Test default creation of empty attribute object and using its method. -- GitLab