PrimeIntellect/SWE-rebench-V2 huggingface dataset:
Repository: twigphp/Twig (php)

Issue:
Null-coalescing does not work when method returns null
```twig
{{ something.nice(category) ?? 'nope' }}
```
should return `nope` but the result is empty

tried to add a test to `tests/IntegrationTest.php` but not sure how to inject an object for `tests/Fixtures/tests/null_coalesce.test`

this broke my code after latest release: i had a function where it accepts only string type but then the null coalesce stopped working and null was passed instead of the fallback string

Pull request:
Fix the null coalescing operator when the test returns null
Closes #4499

Patch:
diff --git a/CHANGELOG b/CHANGELOG
index d6bf5cbd..b0520220 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 6fb088fa..15b6e8ee 100644
--- a/src/Node/Expression/Binary/NullCoalesceBinary.php
+++ b/src/Node/Expression/Binary/NullCoalesceBinary.php
@@ -29,8 +29,7 @@ final class NullCoalesceBinary extends AbstractBinary implements OperatorEscapeI
         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(


Test patch:
diff --git a/tests/Fixtures/tests/null_coalesce.test b/tests/Fixtures/tests/null_coalesce.test
index f80b9071..b73ec463 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 49ccf76c..2a88c6af 100644
--- a/tests/IntegrationTest.php
+++ b/tests/IntegrationTest.php
@@ -77,6 +77,16 @@ class TwigTestFoo implements \Iterator
         return 'foo';
     }
 
+    public function getEmpty()
+    {
+        return '';
+    }
+
+    public function getNull()
+    {
+        return null;
+    }
+
     public function getSelf()
     {
         return $this;