Skip to content

Commit 8d0a98d

Browse files
committed
[TypeDeclaration] Skip return interface on NarrowObjectReturnTypeRector
1 parent 1a19a34 commit 8d0a98d

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\NarrowObjectReturnTypeRector\Fixture;
4+
5+
use Psr\Log\LoggerInterface;
6+
use Psr\Log\NullLogger;
7+
8+
final class SkipReturnInterface
9+
{
10+
protected function build(): LoggerInterface
11+
{
12+
return new NullLogger();
13+
}
14+
}

rules/TypeDeclaration/Rector/ClassMethod/NarrowObjectReturnTypeRector.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,16 @@
3333
*/
3434
final class NarrowObjectReturnTypeRector extends AbstractRector
3535
{
36+
/**
37+
* List of interfaces that usually use non-mocked on tests
38+
*
39+
* @var class-string[]
40+
*/
41+
private const ALLOWED_INTERFACES_CHANGE = [
42+
'Doctrine\Common\Collections\Collection',
43+
'PhpParser\Node',
44+
];
45+
3646
public function __construct(
3747
private readonly BetterNodeFinder $betterNodeFinder,
3848
private readonly ReflectionResolver $reflectionResolver,
@@ -151,13 +161,29 @@ public function refactor(Node $node): ?Node
151161
return null;
152162
}
153163

164+
if (! in_array($declaredType, self::ALLOWED_INTERFACES_CHANGE, true) && $this->isInterface($declaredType)) {
165+
return null;
166+
}
167+
154168
$node->returnType = new FullyQualified($actualReturnClass);
155169

156170
$this->updateDocblock($node, $actualReturnClass);
157171

158172
return $node;
159173
}
160174

175+
private function isInterface(string $declaredType): bool
176+
{
177+
$declaredObjectType = new ObjectType($declaredType);
178+
$classReflection = $declaredObjectType->getClassReflection();
179+
180+
if (! $classReflection instanceof ClassReflection) {
181+
return false;
182+
}
183+
184+
return $classReflection->isInterface();
185+
}
186+
161187
private function updateDocblock(ClassMethod $classMethod, string $actualReturnClass): void
162188
{
163189
$phpDocInfo = $this->phpDocInfoFactory->createFromNode($classMethod);

0 commit comments

Comments
 (0)