Skip to content

Commit 613b2d4

Browse files
panzer-punkDaniiltaylorotwell
authored
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 <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent c500a22 commit 613b2d4

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/Support/ReflectionClosure.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -508,7 +508,7 @@ public function getCode()
508508
break;
509509
case 'id_name':
510510
switch ($token[0]) {
511-
case $token[0] === ':' && $context !== 'instanceof':
511+
case $token[0] === ':' && ! in_array($context, ['instanceof', 'new'], true):
512512
if ($lastState === 'closure' && $context === 'root') {
513513
$state = 'closure';
514514
$code .= $id_start.$token;

tests/ReflectionClosure5Test.php

+16
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Foo\Baz\Qux\Forest;
66
use Laravel\SerializableClosure\Support\ReflectionClosure;
77
use Tests\Fixtures\Model;
8+
use Tests\Fixtures\RegularClass;
89

910
test('is short closure', function () {
1011
$f1 = fn () => 1;
@@ -243,6 +244,21 @@ public function qux(\Foo\Bar\Qux $qux): \Foo\Bar\Qux
243244
expect($f)->toBeCode($e);
244245
});
245246

247+
test('ternanry operator new without constructor', function () {
248+
$f = function () {
249+
$flag = true;
250+
251+
return $flag ? new RegularClass : new RegularClass;
252+
};
253+
$e = 'function () {
254+
$flag = true;
255+
256+
return $flag ? new \Tests\Fixtures\RegularClass : new \Tests\Fixtures\RegularClass;
257+
}';
258+
259+
expect($f)->toBeCode($e);
260+
});
261+
246262
// Helpers
247263
function c(Closure $closure)
248264
{

0 commit comments

Comments
 (0)