Skip to content

Commit

Permalink
Fix broken code for ternary operator with class instantiation with om…
Browse files Browse the repository at this point in the history
…itted 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]>
  • Loading branch information
3 people authored Dec 16, 2024
1 parent c500a22 commit 613b2d4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Support/ReflectionClosure.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 16 additions & 0 deletions tests/ReflectionClosure5Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand Down

0 comments on commit 613b2d4

Please sign in to comment.