From 4c5467f56aa085c721da132014cc968af1f4b508 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 12 Dec 2024 08:34:15 +0100 Subject: [PATCH] Fix the null coalescing operator when the test returns null --- CHANGELOG | 1 + src/Node/Expression/Binary/NullCoalesceBinary.php | 3 +-- tests/Fixtures/tests/null_coalesce.test | 5 ++++- tests/IntegrationTest.php | 10 ++++++++++ 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index d6bf5cbd45a..b0520220415 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ # 3.17.1 (2024-XX-XX) + * Fix the null coalescing operator when the test returns null * Fix the Elvis operator when used as '? :' instead of '?:' # 3.17.0 (2024-12-10) diff --git a/src/Node/Expression/Binary/NullCoalesceBinary.php b/src/Node/Expression/Binary/NullCoalesceBinary.php index 6fb088fa62d..15b6e8ee937 100644 --- a/src/Node/Expression/Binary/NullCoalesceBinary.php +++ b/src/Node/Expression/Binary/NullCoalesceBinary.php @@ -29,8 +29,7 @@ public function __construct(AbstractExpression $left, AbstractExpression $right, parent::__construct($left, $right, $lineno); if (!$left instanceof NameExpression) { - $left = clone $left; - $test = new DefinedTest($left, new TwigTest('defined'), new EmptyNode(), $left->getTemplateLine()); + $test = new DefinedTest(clone $left, new TwigTest('defined'), new EmptyNode(), $left->getTemplateLine()); // for "block()", we don't need the null test as the return value is always a string if (!$left instanceof BlockReferenceExpression) { $test = new AndBinary( diff --git a/tests/Fixtures/tests/null_coalesce.test b/tests/Fixtures/tests/null_coalesce.test index f80b907178d..b73ec4634d8 100644 --- a/tests/Fixtures/tests/null_coalesce.test +++ b/tests/Fixtures/tests/null_coalesce.test @@ -13,8 +13,10 @@ Twig supports the ?? operator {{ nope ?? (nada ?? 'OK') }} {{ 1 + (nope ?? (nada ?? 2)) }} {{ 1 + (nope ?? 3) + (nada ?? 2) }} +{{ obj.null() ?? 'OK' }} +{{ obj.empty() ?? 'KO' }} --DATA-- -return ['bar' => 'OK', 'foo' => ['bar' => 'OK']] +return ['bar' => 'OK', 'foo' => ['bar' => 'OK'], 'obj' => new Twig\Tests\TwigTestFoo()] --EXPECT-- OK OK @@ -28,3 +30,4 @@ OK OK 3 6 +OK diff --git a/tests/IntegrationTest.php b/tests/IntegrationTest.php index 49ccf76cb96..2a88c6af203 100644 --- a/tests/IntegrationTest.php +++ b/tests/IntegrationTest.php @@ -77,6 +77,16 @@ public function getFoo() return 'foo'; } + public function getEmpty() + { + return ''; + } + + public function getNull() + { + return null; + } + public function getSelf() { return $this;