From 613b2d4998f85564d40497e05e89cb6d9bd1cbe8 Mon Sep 17 00:00:00 2001 From: Daniil_Budarnyy Date: Mon, 16 Dec 2024 18:26:28 +0300 Subject: [PATCH] Fix broken code for ternary operator with class instantiation with omitted parentheses (#102) * Fix ReflectionClosure wrong code for new without constructor in ternary * Fix strict comparsion for in_array * Update ReflectionClosure.php --------- Co-authored-by: Daniil Co-authored-by: Taylor Otwell --- src/Support/ReflectionClosure.php | 2 +- tests/ReflectionClosure5Test.php | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/Support/ReflectionClosure.php b/src/Support/ReflectionClosure.php index 9c5f3b0d..8bf13ac0 100644 --- a/src/Support/ReflectionClosure.php +++ b/src/Support/ReflectionClosure.php @@ -508,7 +508,7 @@ public function getCode() break; case 'id_name': switch ($token[0]) { - case $token[0] === ':' && $context !== 'instanceof': + case $token[0] === ':' && ! in_array($context, ['instanceof', 'new'], true): if ($lastState === 'closure' && $context === 'root') { $state = 'closure'; $code .= $id_start.$token; diff --git a/tests/ReflectionClosure5Test.php b/tests/ReflectionClosure5Test.php index 2919d45b..cbf411ac 100644 --- a/tests/ReflectionClosure5Test.php +++ b/tests/ReflectionClosure5Test.php @@ -5,6 +5,7 @@ use Foo\Baz\Qux\Forest; use Laravel\SerializableClosure\Support\ReflectionClosure; use Tests\Fixtures\Model; +use Tests\Fixtures\RegularClass; test('is short closure', function () { $f1 = fn () => 1; @@ -243,6 +244,21 @@ public function qux(\Foo\Bar\Qux $qux): \Foo\Bar\Qux expect($f)->toBeCode($e); }); +test('ternanry operator new without constructor', function () { + $f = function () { + $flag = true; + + return $flag ? new RegularClass : new RegularClass; + }; + $e = 'function () { + $flag = true; + + return $flag ? new \Tests\Fixtures\RegularClass : new \Tests\Fixtures\RegularClass; + }'; + + expect($f)->toBeCode($e); +}); + // Helpers function c(Closure $closure) {