Skip to content

Commit

Permalink
Fix false positive with `reportPossiblyNonexistentConstantArrayOffset…
Browse files Browse the repository at this point in the history
…: true`
  • Loading branch information
ondrejmirtes committed May 13, 2024
1 parent 3f7d006 commit 5277630
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Type/Constant/ConstantArrayType.php
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,17 @@ public function hasOffsetValueType(Type $offsetType): TrinaryLogic

return TrinaryLogic::extremeIdentity(...$results);
}
if ($offsetType instanceof IntegerRangeType) {
$finiteTypes = $offsetType->getFiniteTypes();
if ($finiteTypes !== []) {
$results = [];
foreach ($finiteTypes as $innerType) {
$results[] = $this->hasOffsetValueType($innerType);
}

return TrinaryLogic::extremeIdentity(...$results);
}
}

$result = TrinaryLogic::createNo();
foreach ($this->keyTypes as $i => $keyType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -853,4 +853,15 @@ public function testReportPossiblyNonexistentArrayOffset(bool $reportPossiblyNon
$this->analyse([__DIR__ . '/data/report-possibly-nonexistent-array-offset.php'], $errors);
}

public function testBug10997(): void
{
$this->reportPossiblyNonexistentConstantArrayOffset = true;
$this->analyse([__DIR__ . '/data/bug-10997.php'], [
[
'Offset int<0, 4> might not exist on array{1, 2, 3, 4}.',
15,
],
]);
}

}
17 changes: 17 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/bug-10997.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Bug10997;

function (): void {
$array = [1, 2, 3, 4];
for ($i = 0; $i < count($array); ++$i) {
echo $array[$i], "\n";
}
};

function (): void {
$array = [1, 2, 3, 4];
for ($i = 0; $i < 5; ++$i) {
echo $array[$i], "\n";
}
};

0 comments on commit 5277630

Please sign in to comment.