Skip to content

Commit

Permalink
[TypeDeclaration] Add return self object support on ReturnTypeFromStr…
Browse files Browse the repository at this point in the history
…ictFluentReturnRector (#4915)
  • Loading branch information
samsonasik authored Sep 5, 2023
1 parent 093bcb6 commit 6d009cc
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictFluentReturnRector\Fixture;

final class ReturnSelf
{
private $foo = 'bar';

public function test()
{
$obj = new self();
$obj->foo = 'foo';

return $obj;
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictFluentReturnRector\Fixture;

final class ReturnSelf
{
private $foo = 'bar';

public function test(): self
{
$obj = new self();
$obj->foo = 'foo';

return $obj;
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit 6d009cc

Please sign in to comment.