Skip to content

Commit 157504c

Browse files
authored
[TypeDeclaration] Skip no key generic object return on NarrowObjectReturnTypeRector (#7623)
1 parent 5aba21f commit 157504c

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\NarrowObjectReturnTypeRector\Fixture;
4+
5+
final class SkipNoKeyGenericObjectReturnDoc
6+
{
7+
/**
8+
* @return \Iterator<\stdClass>
9+
*/
10+
public function run(): \Iterator
11+
{
12+
$arr = [new \stdClass];
13+
return new \ArrayIterator($arr);
14+
}
15+
}

rules/TypeDeclaration/Rector/ClassMethod/NarrowObjectReturnTypeRector.php

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
1313
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
1414
use PHPStan\Reflection\ClassReflection;
15+
use PHPStan\Type\Generic\GenericObjectType;
1516
use PHPStan\Type\ObjectType;
1617
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
1718
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
@@ -147,7 +148,7 @@ public function refactor(Node $node): ?Node
147148
return null;
148149
}
149150

150-
if (! $this->isNarrowingValid($declaredType, $actualReturnClass)) {
151+
if (! $this->isNarrowingValid($node, $declaredType, $actualReturnClass)) {
151152
return null;
152153
}
153154

@@ -228,7 +229,7 @@ private function isActualTypeAnonymous(string $actualType): bool
228229
return $classReflection->isAnonymous();
229230
}
230231

231-
private function isNarrowingValid(string $declaredType, string $actualType): bool
232+
private function isNarrowingValid(ClassMethod $classMethod, string $declaredType, string $actualType): bool
232233
{
233234
if ($declaredType === 'object') {
234235
return true;
@@ -237,8 +238,18 @@ private function isNarrowingValid(string $declaredType, string $actualType): boo
237238
$actualObjectType = new ObjectType($actualType);
238239
$declaredObjectType = new ObjectType($declaredType);
239240

240-
return $declaredObjectType->isSuperTypeOf($actualObjectType)
241-
->yes();
241+
if (! $declaredObjectType->isSuperTypeOf($actualObjectType)
242+
->yes()) {
243+
return false;
244+
}
245+
246+
$phpDocInfo = $this->phpDocInfoFactory->createFromNode($classMethod);
247+
if (! $phpDocInfo instanceof PhpDocInfo) {
248+
return true;
249+
}
250+
251+
$returnType = $phpDocInfo->getReturnType();
252+
return ! $returnType instanceof GenericObjectType;
242253
}
243254

244255
private function hasParentMethodWithNonObjectReturn(ClassMethod $classMethod): bool

0 commit comments

Comments
 (0)