Skip to content

Commit 8a5bfb9

Browse files
committed
Do not union array shape with empty array, use optional offset instead
1 parent 484574b commit 8a5bfb9

File tree

4 files changed

+26
-4
lines changed

4 files changed

+26
-4
lines changed

phpstan-baseline.neon

+1-1
Original file line numberDiff line numberDiff line change
@@ -1698,7 +1698,7 @@ parameters:
16981698
-
16991699
message: '#^Doing instanceof PHPStan\\Type\\Constant\\ConstantArrayType is error\-prone and deprecated\. Use Type\:\:getConstantArrays\(\) instead\.$#'
17001700
identifier: phpstanApi.instanceofType
1701-
count: 14
1701+
count: 16
17021702
path: src/Type/TypeCombinator.php
17031703

17041704
-

src/PhpDoc/TypeNodeResolver.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -674,8 +674,8 @@ static function (string $variance): TemplateTypeVariance {
674674
&& ($finiteTypes[0] instanceof ConstantStringType || $finiteTypes[0] instanceof ConstantIntegerType)
675675
) {
676676
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
677-
$arrayBuilder->setOffsetValueType($finiteTypes[0], $genericTypes[1]);
678-
$arrayType = TypeCombinator::union($arrayBuilder->getArray(), ConstantArrayTypeBuilder::createEmpty()->getArray());
677+
$arrayBuilder->setOffsetValueType($finiteTypes[0], $genericTypes[1], true);
678+
$arrayType = $arrayBuilder->getArray();
679679
} else {
680680
$arrayType = new ArrayType($keyType, $genericTypes[1]);
681681
}

src/Type/TypeCombinator.php

+22
Original file line numberDiff line numberDiff line change
@@ -1216,6 +1216,28 @@ public static function intersect(Type ...$types): Type
12161216
continue 2;
12171217
}
12181218

1219+
if (
1220+
$types[$i] instanceof ConstantArrayType
1221+
&& count($types[$i]->getKeyTypes()) === 1
1222+
&& $types[$j] instanceof NonEmptyArrayType
1223+
) {
1224+
$types[$i] = $types[$i]->makeOffsetRequired($types[$i]->getKeyTypes()[0]);
1225+
array_splice($types, $j--, 1);
1226+
$typesCount--;
1227+
continue;
1228+
}
1229+
1230+
if (
1231+
$types[$j] instanceof ConstantArrayType
1232+
&& count($types[$j]->getKeyTypes()) === 1
1233+
&& $types[$i] instanceof NonEmptyArrayType
1234+
) {
1235+
$types[$j] = $types[$j]->makeOffsetRequired($types[$j]->getKeyTypes()[0]);
1236+
array_splice($types, $i--, 1);
1237+
$typesCount--;
1238+
continue 2;
1239+
}
1240+
12191241
if ($types[$i] instanceof ConstantArrayType && $types[$j] instanceof HasOffsetValueType) {
12201242
$offsetType = $types[$j]->getOffsetType();
12211243
$valueType = $types[$j]->getValueType();

tests/PHPStan/Analyser/nsrt/array-shape-from-general-array-with-single-finite-key.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class Foo
1212
*/
1313
public function doFoo(array $a): void
1414
{
15-
assertType('array{}|array{1: string}', $a);
15+
assertType('array{1?: string}', $a);
1616
}
1717

1818
/**

0 commit comments

Comments
 (0)