diff --git a/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector/Fixture/include_simple_array_shape.php.inc b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector/Fixture/include_simple_array_shape.php.inc new file mode 100644 index 00000000000..aa7194c9e9c --- /dev/null +++ b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector/Fixture/include_simple_array_shape.php.inc @@ -0,0 +1,46 @@ + +----- + diff --git a/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector/Fixture/make_complex_array_shape_simpler.php.inc b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector/Fixture/make_complex_array_shape_simpler.php.inc new file mode 100644 index 00000000000..849d3e20199 --- /dev/null +++ b/rules-tests/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector/Fixture/make_complex_array_shape_simpler.php.inc @@ -0,0 +1,50 @@ + +----- + diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector.php index df09d3ec65f..46012ec13ae 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictNewArrayRector.php @@ -18,6 +18,7 @@ use PhpParser\Node\Stmt\Function_; use PhpParser\Node\Stmt\Return_; use PHPStan\Type\ArrayType; use PHPStan\Type\Constant\ConstantArrayType; +use PHPStan\Type\MixedType; use PHPStan\Type\NeverType; use PHPStan\Type\Type; use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger; @@ -129,6 +130,9 @@ CODE_SAMPLE if ($this->shouldAddReturnArrayDocType($exprType)) { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); + + $exprType = $this->narrowConstantArrayType($exprType); + $this->phpDocTypeChanger->changeReturnType($phpDocInfo, $exprType); } @@ -202,4 +206,17 @@ CODE_SAMPLE return $exprType instanceof ArrayType; } + + private function narrowConstantArrayType(Type $type): Type + { + if (! $type instanceof ConstantArrayType) { + return $type; + } + + if (count($type->getValueTypes()) > 3) { + return new ArrayType(new MixedType(), new MixedType()); + } + + return $type; + } }