[TypeDeclaration] Add more precise array type doc (#2575)

* [TypeDeclaration] Add more precise array type doc

* [ci-review] Rector Rectify

Co-authored-by: GitHub Action <action@github.com>
This commit is contained in:
Tomas Votruba 2022-06-26 16:37:53 +02:00 committed by GitHub
parent a11dd6a534
commit 59ed8480e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 113 additions and 0 deletions

View File

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector\Fixture;
final class IncludeSimpleArrayShape
{
public function run()
{
$items = [];
$items['one'] = 1;
$items['two'] = 1;
$items['three'] = 1;
return $items;
}
}
?>
-----
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector\Fixture;
final class IncludeSimpleArrayShape
{
/**
* @return array{one: int, two: int, three: int}
*/
public function run(): array
{
$items = [];
$items['one'] = 1;
$items['two'] = 1;
$items['three'] = 1;
return $items;
}
}
?>

View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector\Fixture;
final class MakeComplexArrayShapeSimpler
{
public function run()
{
$items = [];
$items['one'] = 1;
$items['two'] = 1;
$items['three'] = 1;
$items['four'] = 1;
$items['five'] = 1;
return $items;
}
}
?>
-----
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector\Fixture;
final class MakeComplexArrayShapeSimpler
{
/**
* @return mixed[]
*/
public function run(): array
{
$items = [];
$items['one'] = 1;
$items['two'] = 1;
$items['three'] = 1;
$items['four'] = 1;
$items['five'] = 1;
return $items;
}
}
?>

View File

@ -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;
}
}