diff --git a/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector/Fixture/return_self.php.inc b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector/Fixture/return_self.php.inc new file mode 100644 index 00000000000..c7bd4073378 --- /dev/null +++ b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector/Fixture/return_self.php.inc @@ -0,0 +1,37 @@ +foo = 'foo'; + + return $obj; + } +} + +?> +----- +foo = 'foo'; + + return $obj; + } +} + +?> diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector.php index a36c3589a30..2ca50ab7f52 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictFluentReturnRector.php @@ -9,6 +9,7 @@ use PhpParser\Node\Stmt\ClassMethod; use PHPStan\Analyser\Scope; use PHPStan\Reflection\ClassReflection; +use PHPStan\Type\ObjectType; use PHPStan\Type\ThisType; use Rector\Core\Php\PhpVersionProvider; use Rector\Core\Rector\AbstractScopeAwareRector; @@ -86,14 +87,18 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node return null; } - $returnType = $this->returnTypeInferer->inferFunctionLike($node); - - if (! $returnType instanceof ThisType) { + $classReflection = $this->reflectionResolver->resolveClassReflection($node); + if (! $classReflection instanceof ClassReflection) { return null; } - $classReflection = $this->reflectionResolver->resolveClassReflection($node); - if (! $classReflection instanceof ClassReflection) { + $returnType = $this->returnTypeInferer->inferFunctionLike($node); + if ($returnType instanceof ObjectType && $returnType->getClassName() === $classReflection->getName()) { + $node->returnType = new Name('self'); + return $node; + } + + if (! $returnType instanceof ThisType) { return null; }