Skip to content

Commit

Permalink
Fix the null coalescing operator when the test returns null
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Dec 12, 2024
1 parent 47f527e commit 4c5467f
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 4c5467f

Please sign in to comment.