Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector\Fixture;

final class UnionArrayShapesNoDoc
{
public function getRowFormatBookEntry($abe, $onlyCashRegister = false)
{
$data = [];
foreach ($abe as $x) {
if ($onlyCashRegister) {
$data[] = ['amount' => 1, 'cash_register_id' => 2, 'text' => 't'];
} else {
$data[] = ['amount' => 1, 'date' => 'd', 'text' => 't'];
}
}

return $data;
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictNewArrayRector\Fixture;

final class UnionArrayShapesNoDoc
{
public function getRowFormatBookEntry($abe, $onlyCashRegister = false): array
{
$data = [];
foreach ($abe as $x) {
if ($onlyCashRegister) {
$data[] = ['amount' => 1, 'cash_register_id' => 2, 'text' => 't'];
} else {
$data[] = ['amount' => 1, 'date' => 'd', 'text' => 't'];
}
}

return $data;
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\UnionType;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\NodeNameResolver\NodeNameResolver;
Expand Down Expand Up @@ -202,6 +204,11 @@ private function matchArrayAssignedVariable(array $stmts): array

private function shouldAddReturnArrayDocType(Type $arrayType): bool
{
// a union of multiple distinct array shapes produces a noisy doc type, skip it
if ($this->hasNoisyArrayShapeUnion($arrayType)) {
return false;
}

if ($arrayType instanceof ConstantArrayType) {
if ($arrayType->getIterableValueType() instanceof NeverType) {
return false;
Expand All @@ -215,4 +222,37 @@ private function shouldAddReturnArrayDocType(Type $arrayType): bool

return true;
}

private function hasNoisyArrayShapeUnion(Type $type): bool
{
$isNoisy = false;
TypeTraverser::map($type, function (Type $currentType, callable $traverse) use (&$isNoisy): Type {
if ($currentType instanceof UnionType && $this->hasMultipleArrayVariants($currentType)) {
$isNoisy = true;
}

return $traverse($currentType);
});

return $isNoisy;
}

private function hasMultipleArrayVariants(UnionType $unionType): bool
{
$arrayVariantCount = 0;
foreach ($unionType->getTypes() as $type) {
if (! $type->isArray()->yes()) {
continue;
}

// an empty array [] collapses into the sibling variant, ignore it
if ($type->getIterableValueType() instanceof NeverType) {
continue;
}

++$arrayVariantCount;
}

return $arrayVariantCount >= 2;
}
}
Loading