Skip to content

Commit

Permalink
bug #4500 Fix the null coalescing operator when the test returns null…
Browse files Browse the repository at this point in the history
… (fabpot)

This PR was merged into the 3.x branch.

Discussion
----------

Fix the null coalescing operator when the test returns null

Closes #4499

Commits
-------

4c5467f Fix the null coalescing operator when the test returns null
  • Loading branch information
fabpot committed Dec 12, 2024
2 parents 47f527e + 4c5467f commit 243f5f5
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
3 changes: 1 addition & 2 deletions src/Node/Expression/Binary/NullCoalesceBinary.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
5 changes: 4 additions & 1 deletion tests/Fixtures/tests/null_coalesce.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -28,3 +30,4 @@ OK
OK
3
6
OK
10 changes: 10 additions & 0 deletions tests/IntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ public function getFoo()
return 'foo';
}

public function getEmpty()
{
return '';
}

public function getNull()
{
return null;
}

public function getSelf()
{
return $this;
Expand Down

0 comments on commit 243f5f5

Please sign in to comment.