Skip to content

Commit b44797e

Browse files
Fix count inferences
1 parent 5a50985 commit b44797e

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
@@ -1106,6 +1106,7 @@ private function specifyTypesForCountFuncCall(
11061106
if (
11071107
$sizeType instanceof ConstantIntegerType
11081108
&& $sizeType->getValue() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1109+
&& $isList->yes()
11091110
&& $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, $sizeType->getValue() - 1))->yes()
11101111
) {
11111112
// turn optional offsets non-optional
@@ -1122,6 +1123,7 @@ private function specifyTypesForCountFuncCall(
11221123
$sizeType instanceof IntegerRangeType
11231124
&& $sizeType->getMin() !== null
11241125
&& $sizeType->getMin() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1126+
&& $isList->yes()
11251127
&& $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, ($sizeType->getMax() ?? $sizeType->getMin()) - 1))->yes()
11261128
) {
11271129
$builderData = [];
@@ -1167,7 +1169,7 @@ private function specifyTypesForCountFuncCall(
11671169
continue;
11681170
}
11691171

1170-
$resultTypes[] = $arrayType;
1172+
$resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
11711173
}
11721174

11731175
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)