1212use PHPStan \PhpDocParser \Ast \Type \GenericTypeNode ;
1313use PHPStan \PhpDocParser \Ast \Type \IdentifierTypeNode ;
1414use PHPStan \Reflection \ClassReflection ;
15+ use PHPStan \Type \Generic \GenericObjectType ;
1516use PHPStan \Type \ObjectType ;
1617use Rector \BetterPhpDocParser \PhpDocInfo \PhpDocInfo ;
1718use 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