Skip to content

Commit 8c960f3

Browse files
authored
[CodeQuality] Skip trailing comment after return in WillReturnCallbackFallbackToReturnFalseRector (#800)
1 parent 518faec commit 8c960f3

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\WillReturnCallbackFallbackToReturnFalseRector\Fixture;
4+
5+
use PHPUnit\Framework\TestCase;
6+
7+
final class SkipTrailingCommentAfterReturn extends TestCase
8+
{
9+
public function test()
10+
{
11+
$callSequence = [];
12+
13+
$queueMock = $this->createMock(\stdClass::class);
14+
$queueMock->expects($this->atLeastOnce())->method('isEmpty')->willReturnCallback(static function () use (&$callSequence): bool {
15+
$callSequence[] = 'isEmpty';
16+
17+
return true; // Exit loop immediately
18+
});
19+
}
20+
}

‎rules/CodeQuality/Rector/MethodCall/WillReturnCallbackFallbackToReturnFalseRector.php‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use PhpParser\Node\Expr\Closure;
99
use PhpParser\Node\Expr\ConstFetch;
1010
use PhpParser\Node\Expr\MethodCall;
11+
use PhpParser\Node\Stmt\Nop;
1112
use PhpParser\Node\Stmt\Return_;
1213
use Rector\PhpParser\Node\BetterNodeFinder;
1314
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
@@ -123,8 +124,10 @@ public function refactor(Node $node): ?MethodCall
123124
return null;
124125
}
125126

126-
// already ends with an explicit return, no fallback needed
127-
$lastStmt = $closure->stmts[count($closure->stmts) - 1];
127+
// already ends with an explicit return, no fallback needed;
128+
// skip trailing comment-only Nop statements added by a trailing comment
129+
$stmts = array_filter($closure->stmts, static fn (Node $stmt): bool => ! $stmt instanceof Nop);
130+
$lastStmt = end($stmts);
128131
if ($lastStmt instanceof Return_) {
129132
return null;
130133
}

0 commit comments

Comments
 (0)