Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

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

final class ReturnAnonymousClassVariable
{
public function action()
{
$data = new class
{
// any properties
};

// some bussines logic to fill the data

return $data;
}
}

?>
-----
<?php

declare(strict_types=1);

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

final class ReturnAnonymousClassVariable
{
public function action(): object
{
$data = new class
{
// any properties
};

// some bussines logic to fill the data

return $data;
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ public function matchAlwaysReturnVariableNew(ClassMethod|Function_ $functionLike
return null;
}

$returnType = $this->nodeTypeResolver->getType($return->expr);
$returnType = $this->nodeTypeResolver->getNativeType($return->expr);
if ($returnType instanceof \PHPStan\Type\ObjectWithoutClassType) {
$alwaysReturnedClassNames[] = 'object';
continue;
}

if (! $returnType instanceof ObjectType) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use PhpParser\Node;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\ClassMethod;
Expand Down Expand Up @@ -119,6 +120,11 @@ public function refactor(Node $node): ?Node

$returnedNewClassName = $this->strictReturnNewAnalyzer->matchAlwaysReturnVariableNew($node);

if ($returnedNewClassName === 'object') {
$node->returnType = new Identifier('object');
return $node;
}

if (is_string($returnedNewClassName)) {
$node->returnType = new FullyQualified($returnedNewClassName);

Expand Down
Loading