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
Expand Up @@ -19,7 +19,7 @@ function FalseAndTrue()
namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\DocblockReturnArrayFromDirectArrayInstanceRector\Fixture;

/**
* @return array<string, true[]|false[]>
* @return array<string, bool[]>
*/
function FalseAndTrue()
{
Expand Down
40 changes: 38 additions & 2 deletions rules/Privatization/TypeManipulator/TypeNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\UnionType;
use Rector\NodeTypeResolver\PHPStan\Type\TypeFactory;
use Rector\NodeTypeResolver\PHPStan\TypeHasher;
use Rector\StaticTypeMapper\StaticTypeMapper;

final readonly class TypeNormalizer
Expand All @@ -32,7 +33,8 @@
public function __construct(
private TypeFactory $typeFactory,
private StaticTypeMapper $staticTypeMapper,
private ArrayTypeLeastCommonDenominatorResolver $arrayTypeLeastCommonDenominatorResolver
private ArrayTypeLeastCommonDenominatorResolver $arrayTypeLeastCommonDenominatorResolver,
private TypeHasher $typeHasher
) {

}
Expand Down Expand Up @@ -94,7 +96,41 @@ public function generalizeConstantTypes(Type $type): Type
if ($type instanceof UnionType) {
$generalizedUnionedTypes = [];
foreach ($type->getTypes() as $unionedType) {
$generalizedUnionedTypes[] = $this->generalizeConstantTypes($unionedType);
$generalizedUnionedType = $this->generalizeConstantTypes($unionedType);

if ($generalizedUnionedType instanceof ArrayType) {
$keyType = $this->typeHasher->createTypeHash($generalizedUnionedType->getKeyType());

foreach ($generalizedUnionedTypes as $key => $existingUnionedType) {
if (! $existingUnionedType instanceof ArrayType) {
continue;
}

$existingKeyType = $this->typeHasher->createTypeHash(
$existingUnionedType->getKeyType()
);

if ($keyType !== $existingKeyType) {
continue;
}

$uniqueTypes = $this->typeFactory->uniquateTypes(
[$existingUnionedType->getItemType(), $generalizedUnionedType->getItemType()]
);

if (count($uniqueTypes) !== 1) {
continue;
}

$generalizedUnionedTypes[$key] = new ArrayType(
$existingUnionedType->getKeyType(),
$uniqueTypes[0]
);
continue 2;
}
}

$generalizedUnionedTypes[] = $generalizedUnionedType;
}

$uniqueGeneralizedUnionTypes = $this->typeFactory->uniquateTypes($generalizedUnionedTypes);
Expand Down
Loading