Skip to content

Commit

Permalink
[PHPStanStaticTypeMapper] Improve performance of UnionTypeMapper take…
Browse files Browse the repository at this point in the history
… 3 (#3690)
  • Loading branch information
samsonasik committed May 8, 2023
1 parent ae61bb6 commit 5c3fbbe
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions packages/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ public function mapToPhpParserNode(Type $type, string $typeKind): ?Node
public function resolveTypeWithNullablePHPParserUnionType(
PhpParserUnionType $phpParserUnionType
): PhpParserUnionType|NullableType|null {
if (count($phpParserUnionType->types) === 2) {
$totalTypes = count($phpParserUnionType->types);
if ($totalTypes === 2) {
$phpParserUnionType->types = array_values($phpParserUnionType->types);
$firstType = $phpParserUnionType->types[0];
$secondType = $phpParserUnionType->types[1];
Expand All @@ -140,14 +141,14 @@ public function resolveTypeWithNullablePHPParserUnionType(
Assert::isAnyOf($firstType, [Name::class, Identifier::class]);
Assert::isAnyOf($secondType, [Name::class, Identifier::class]);
} catch (InvalidArgumentException) {
return $this->resolveUnionTypes($phpParserUnionType);
return $this->resolveUnionTypes($phpParserUnionType, $totalTypes);
}

$firstTypeValue = $firstType->toString();
$secondTypeValue = $secondType->toString();

if ($firstTypeValue === $secondTypeValue) {
return $this->resolveUnionTypes($phpParserUnionType);
return $this->resolveUnionTypes($phpParserUnionType, $totalTypes);
}

if ($firstTypeValue === 'null') {
Expand All @@ -159,7 +160,7 @@ public function resolveTypeWithNullablePHPParserUnionType(
}
}

return $this->resolveUnionTypes($phpParserUnionType);
return $this->resolveUnionTypes($phpParserUnionType, $totalTypes);
}

private function resolveNullableType(NullableType $nullableType): null|NullableType|PhpParserUnionType
Expand Down Expand Up @@ -240,13 +241,13 @@ private function matchArrayTypes(UnionType $unionType): Identifier | NullableTyp
return new Identifier($type);
}

private function resolveUnionTypes(PhpParserUnionType $phpParserUnionType): ?PhpParserUnionType
private function resolveUnionTypes(PhpParserUnionType $phpParserUnionType, int $totalTypes): ?PhpParserUnionType
{
if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES)) {
return null;
}

if (count($phpParserUnionType->types) === 2) {
if ($totalTypes === 2) {
return $phpParserUnionType;
}

Expand Down

0 comments on commit 5c3fbbe

Please sign in to comment.