2020use PHPStan \Type \NeverType ;
2121use PHPStan \Type \Type ;
2222use PHPStan \Type \TypeCombinator ;
23+ use PHPStan \Type \TypeTraverser ;
24+ use PHPStan \Type \UnionType ;
2325use Rector \BetterPhpDocParser \PhpDocInfo \PhpDocInfoFactory ;
2426use Rector \BetterPhpDocParser \PhpDocManipulator \PhpDocTypeChanger ;
2527use Rector \NodeNameResolver \NodeNameResolver ;
@@ -202,6 +204,11 @@ private function matchArrayAssignedVariable(array $stmts): array
202204
203205 private function shouldAddReturnArrayDocType (Type $ arrayType ): bool
204206 {
207+ // a union of multiple distinct array shapes produces a noisy doc type, skip it
208+ if ($ this ->hasNoisyArrayShapeUnion ($ arrayType )) {
209+ return false ;
210+ }
211+
205212 if ($ arrayType instanceof ConstantArrayType) {
206213 if ($ arrayType ->getIterableValueType () instanceof NeverType) {
207214 return false ;
@@ -215,4 +222,37 @@ private function shouldAddReturnArrayDocType(Type $arrayType): bool
215222
216223 return true ;
217224 }
225+
226+ private function hasNoisyArrayShapeUnion (Type $ type ): bool
227+ {
228+ $ isNoisy = false ;
229+ TypeTraverser ::map ($ type , function (Type $ currentType , callable $ traverse ) use (&$ isNoisy ): Type {
230+ if ($ currentType instanceof UnionType && $ this ->hasMultipleArrayVariants ($ currentType )) {
231+ $ isNoisy = true ;
232+ }
233+
234+ return $ traverse ($ currentType );
235+ });
236+
237+ return $ isNoisy ;
238+ }
239+
240+ private function hasMultipleArrayVariants (UnionType $ unionType ): bool
241+ {
242+ $ arrayVariantCount = 0 ;
243+ foreach ($ unionType ->getTypes () as $ type ) {
244+ if (! $ type ->isArray ()->yes ()) {
245+ continue ;
246+ }
247+
248+ // an empty array [] collapses into the sibling variant, ignore it
249+ if ($ type ->getIterableValueType () instanceof NeverType) {
250+ continue ;
251+ }
252+
253+ ++$ arrayVariantCount ;
254+ }
255+
256+ return $ arrayVariantCount >= 2 ;
257+ }
218258}
0 commit comments