Skip to content

Commit fe8aab8

Browse files
Fix count inferences
1 parent e7febc3 commit fe8aab8

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
@@ -1113,6 +1113,7 @@ private function specifyTypesForCountFuncCall(
11131113
if (
11141114
$sizeType instanceof ConstantIntegerType
11151115
&& $sizeType->getValue() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1116+
&& $isList->yes()
11161117
&& $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, $sizeType->getValue() - 1))->yes()
11171118
) {
11181119
// turn optional offsets non-optional
@@ -1129,6 +1130,7 @@ private function specifyTypesForCountFuncCall(
11291130
$sizeType instanceof IntegerRangeType
11301131
&& $sizeType->getMin() !== null
11311132
&& $sizeType->getMin() < ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1133+
&& $isList->yes()
11321134
&& $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, ($sizeType->getMax() ?? $sizeType->getMin()) - 1))->yes()
11331135
) {
11341136
$builderData = [];
@@ -1174,7 +1176,7 @@ private function specifyTypesForCountFuncCall(
11741176
continue;
11751177
}
11761178

1177-
$resultTypes[] = $arrayType;
1179+
$resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
11781180
}
11791181

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