Skip to content

Commit 3346acb

Browse files
authored
Fix "Offset (int|string) might not exist on array" after array_keys($arr)
1 parent 3b72271 commit 3346acb

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/Analyser/NodeScopeResolver.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6521,6 +6521,23 @@ private function enterForeach(MutatingScope $scope, MutatingScope $originalScope
65216521
}
65226522
}
65236523

6524+
if (
6525+
$stmt->expr instanceof FuncCall
6526+
&& $stmt->expr->name instanceof Name
6527+
&& $stmt->expr->name->toLowerString() === 'array_keys'
6528+
&& $stmt->valueVar instanceof Variable
6529+
) {
6530+
$args = $stmt->expr->getArgs();
6531+
if (count($args) >= 1) {
6532+
$arrayArg = $args[0]->value;
6533+
$scope = $scope->assignExpression(
6534+
new ArrayDimFetch($arrayArg, $stmt->valueVar),
6535+
$scope->getType($arrayArg)->getIterableValueType(),
6536+
$scope->getNativeType($arrayArg)->getIterableValueType(),
6537+
);
6538+
}
6539+
}
6540+
65246541
return $this->processVarAnnotation($scope, $vars, $stmt);
65256542
}
65266543

tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1000,4 +1000,11 @@ public function testBug10492(): void
10001000
]);
10011001
}
10021002

1003+
public function testBug12926(): void
1004+
{
1005+
$this->reportPossiblyNonexistentGeneralArrayOffset = true;
1006+
1007+
$this->analyse([__DIR__ . '/data/bug-12926.php'], []);
1008+
}
1009+
10031010
}
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 Bug12926;
4+
5+
class HelloWorld
6+
{
7+
public function sayHello(array $arr): void
8+
{
9+
foreach (array_keys($arr) as $key) {
10+
var_dump($arr[$key]);
11+
}
12+
}
13+
}

0 commit comments

Comments
 (0)