diff --git a/rules-tests/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector/Fixture/return_variable_use.php.inc b/rules-tests/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector/Fixture/return_variable_use.php.inc new file mode 100644 index 00000000..8291b1b8 --- /dev/null +++ b/rules-tests/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector/Fixture/return_variable_use.php.inc @@ -0,0 +1,44 @@ +createMock('SomeClass') + ->method('someMethod') + ->with($this->callback(function ($arg): bool { + return true; + })) + ->willReturn($anotherValue); + } +} + +?> +----- +createMock('SomeClass') + ->method('someMethod') + ->willReturnCallback(function ($arg) use ($anotherValue): int { + return $anotherValue; + }); + } +} + +?> diff --git a/rules/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector.php b/rules/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector.php index ea0577a5..77011f06 100644 --- a/rules/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector.php +++ b/rules/CodeQuality/Rector/MethodCall/MergeWithCallableAndWillReturnRector.php @@ -6,8 +6,10 @@ use PhpParser\Node; use PhpParser\Node\Arg; +use PhpParser\Node\ClosureUse; use PhpParser\Node\Expr\Closure; use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\Variable; use PhpParser\Node\Identifier; use PhpParser\Node\Stmt\Return_; use Rector\PhpParser\Node\Value\ValueResolver; @@ -141,9 +143,15 @@ public function refactor(Node $node): MethodCall|null $parentCaller->name = new Identifier('willReturnCallback'); $parentCaller->args = [new Arg($innerClosure)]; + if ($returnedExpr instanceof Variable) { + $innerClosure->uses[] = new ClosureUse($returnedExpr); + } + $returnedExprType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($returnedExpr); - $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnedExprType, TypeKind::RETURN); - $innerClosure->returnType = $returnTypeNode instanceof Node ? $returnTypeNode : null; + $innerClosure->returnType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( + $returnedExprType, + TypeKind::RETURN + ); return $parentCaller; }