Skip to content

Commit 5277630

Browse files
committed
Fix false positive with reportPossiblyNonexistentConstantArrayOffset: true
1 parent 3f7d006 commit 5277630

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

src/Type/Constant/ConstantArrayType.php

+11
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,17 @@ public function hasOffsetValueType(Type $offsetType): TrinaryLogic
618618

619619
return TrinaryLogic::extremeIdentity(...$results);
620620
}
621+
if ($offsetType instanceof IntegerRangeType) {
622+
$finiteTypes = $offsetType->getFiniteTypes();
623+
if ($finiteTypes !== []) {
624+
$results = [];
625+
foreach ($finiteTypes as $innerType) {
626+
$results[] = $this->hasOffsetValueType($innerType);
627+
}
628+
629+
return TrinaryLogic::extremeIdentity(...$results);
630+
}
631+
}
621632

622633
$result = TrinaryLogic::createNo();
623634
foreach ($this->keyTypes as $i => $keyType) {

tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php

+11
Original file line numberDiff line numberDiff line change
@@ -853,4 +853,15 @@ public function testReportPossiblyNonexistentArrayOffset(bool $reportPossiblyNon
853853
$this->analyse([__DIR__ . '/data/report-possibly-nonexistent-array-offset.php'], $errors);
854854
}
855855

856+
public function testBug10997(): void
857+
{
858+
$this->reportPossiblyNonexistentConstantArrayOffset = true;
859+
$this->analyse([__DIR__ . '/data/bug-10997.php'], [
860+
[
861+
'Offset int<0, 4> might not exist on array{1, 2, 3, 4}.',
862+
15,
863+
],
864+
]);
865+
}
866+
856867
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Bug10997;
4+
5+
function (): void {
6+
$array = [1, 2, 3, 4];
7+
for ($i = 0; $i < count($array); ++$i) {
8+
echo $array[$i], "\n";
9+
}
10+
};
11+
12+
function (): void {
13+
$array = [1, 2, 3, 4];
14+
for ($i = 0; $i < 5; ++$i) {
15+
echo $array[$i], "\n";
16+
}
17+
};

0 commit comments

Comments
 (0)