Skip to content

Commit ebe21fd

Browse files
committed
Limit int ranges when narrowing arrays via count()
1 parent 0401189 commit ebe21fd

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

src/Analyser/TypeSpecifier.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,6 +1105,8 @@ private function specifyTypesForCountFuncCall(
11051105
if (
11061106
$sizeType instanceof IntegerRangeType
11071107
&& $sizeType->getMin() !== null
1108+
&& $sizeType->getMin() <= ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
1109+
&& ($sizeType->getMax() ?? $sizeType->getMin()) - $sizeType->getMin() <= ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
11081110
&& (
11091111
$isList->yes()
11101112
|| $isConstantArray->yes() && $arrayType->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, $sizeType->getMin() - 1))->yes()

tests/PHPStan/Analyser/AnalyserIntegrationTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,12 @@ public function testBug12159(): void
15421542
$this->assertNoErrors($errors);
15431543
}
15441544

1545+
public function testBug12787(): void
1546+
{
1547+
$errors = $this->runAnalyse(__DIR__ . '/data/bug-12787.php');
1548+
$this->assertNoErrors($errors);
1549+
}
1550+
15451551
/**
15461552
* @param string[]|null $allAnalysedFiles
15471553
* @return Error[]
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug12787;
4+
5+
class HelloWorld
6+
{
7+
protected const MAX_COUNT = 100000000;
8+
9+
/**
10+
* @return string[]
11+
*/
12+
public function accumulate(): array
13+
{
14+
$items = [];
15+
16+
do {
17+
$items[] = 'something';
18+
} while (count($items) < self::MAX_COUNT);
19+
20+
return $items;
21+
}
22+
}

0 commit comments

Comments
 (0)