Skip to content

Commit 15cda6e

Browse files
VincentLangletondrejmirtes
authored andcommitted
Fix count inferences
1 parent e15206b commit 15cda6e

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

src/Analyser/TypeSpecifier.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1107,6 +1107,7 @@ private function specifyTypesForCountFuncCall(
11071107
if (
11081108
$sizeType instanceof ConstantIntegerType
11091109
&& $sizeType->getValue() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1110+
&& $isList->yes()
11101111
&& $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, $sizeType->getValue() - 1))->yes()
11111112
) {
11121113
// turn optional offsets non-optional
@@ -1123,6 +1124,7 @@ private function specifyTypesForCountFuncCall(
11231124
$sizeType instanceof IntegerRangeType
11241125
&& $sizeType->getMin() !== null
11251126
&& $sizeType->getMin() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1127+
&& $isList->yes()
11261128
&& $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, ($sizeType->getMax() ?? $sizeType->getMin()) - 1))->yes()
11271129
) {
11281130
$builderData = [];
@@ -1168,7 +1170,7 @@ private function specifyTypesForCountFuncCall(
11681170
continue;
11691171
}
11701172

1171-
$resultTypes[] = $arrayType;
1173+
$resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
11721174
}
11731175

11741176
return $this->create($countFuncCall->getArgs()[0]->value, TypeCombinator::union(...$resultTypes), $context, $scope)->setRootExpr($rootExpr);
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug13111;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/** @return array{0?: string, 1?: int} */
8+
function foo() { return [1 => 8]; }
9+
10+
$b = foo();
11+
if (count($b) === 1) {
12+
assertType('non-empty-array{0?: string, 1?: int}', $b);
13+
}

tests/PHPStan/Analyser/nsrt/list-count.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ protected function testOptionalKeysInUnionListWithIntRange($row, $listRow, $twoO
407407
protected function testOptionalKeysInUnionArrayWithIntRange($row, $twoOrThree): void
408408
{
409409
if (count($row) >= $twoOrThree) {
410-
assertType('array{0: int, 1: string|null, 2?: int|null}', $row);
410+
assertType('array{0: int, 1?: string|null, 2?: int|null, 3?: float|null}', $row);
411411
} else {
412412
assertType('array{0: int, 1?: string|null, 2?: int|null, 3?: float|null}|array{string}', $row);
413413
}

0 commit comments

Comments
 (0)