Skip to content

Commit a9a9630

Browse files
authored
Faster TypeCombinator (#5934)
1 parent 29140da commit a9a9630

2 files changed

Lines changed: 24 additions & 17 deletions

File tree

phpstan-baseline.neon

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1656,7 +1656,7 @@ parameters:
16561656
-
16571657
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantArrayType is error-prone and deprecated. Use Type::getConstantArrays() instead.'
16581658
identifier: phpstanApi.instanceofType
1659-
count: 21
1659+
count: 22
16601660
path: src/Type/TypeCombinator.php
16611661

16621662
-

src/Type/TypeCombinator.php

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1609,9 +1609,14 @@ public static function intersect(Type ...$types): Type
16091609
$newTypes = [];
16101610
$hasOffsetValueTypeCount = 0;
16111611
$typesCount = count($types);
1612+
$typesNeedSorting = false;
16121613
for ($i = 0; $i < $typesCount; $i++) {
16131614
$type = $types[$i];
16141615

1616+
if ($type instanceof SubtractableType || $type instanceof ConstantArrayType) {
1617+
$typesNeedSorting = true;
1618+
}
1619+
16151620
if ($type instanceof IntersectionType && !$type instanceof TemplateType) {
16161621
// transform A & (B & C) to A & B & C
16171622
array_splice($types, $i--, 1, $type->getTypes());
@@ -1629,24 +1634,26 @@ public static function intersect(Type ...$types): Type
16291634
$typesCount = count($types);
16301635
}
16311636

1632-
usort($types, static function (Type $a, Type $b): int {
1633-
// move subtractables with subtracts before those without to avoid losing them in the union logic
1634-
if ($a instanceof SubtractableType && $a->getSubtractedType() !== null) {
1635-
return -1;
1636-
}
1637-
if ($b instanceof SubtractableType && $b->getSubtractedType() !== null) {
1638-
return 1;
1639-
}
1637+
if ($typesNeedSorting) {
1638+
usort($types, static function (Type $a, Type $b): int {
1639+
// move subtractables with subtracts before those without to avoid losing them in the union logic
1640+
if ($a instanceof SubtractableType && $a->getSubtractedType() !== null) {
1641+
return -1;
1642+
}
1643+
if ($b instanceof SubtractableType && $b->getSubtractedType() !== null) {
1644+
return 1;
1645+
}
16401646

1641-
if ($a instanceof ConstantArrayType && !$b instanceof ConstantArrayType) {
1642-
return -1;
1643-
}
1644-
if ($b instanceof ConstantArrayType && !$a instanceof ConstantArrayType) {
1645-
return 1;
1646-
}
1647+
if ($a instanceof ConstantArrayType && !$b instanceof ConstantArrayType) {
1648+
return -1;
1649+
}
1650+
if ($b instanceof ConstantArrayType && !$a instanceof ConstantArrayType) {
1651+
return 1;
1652+
}
16471653

1648-
return 0;
1649-
});
1654+
return 0;
1655+
});
1656+
}
16501657

16511658
// transform IntegerType & ConstantIntegerType to ConstantIntegerType
16521659
// transform Child & Parent to Child

0 commit comments

Comments
 (0)