From c609d284e0610b7dba19c2093fe96a7445bc6cae Mon Sep 17 00:00:00 2001 From: Markus Staab Date: Sun, 28 Sep 2025 11:14:39 +0200 Subject: [PATCH 1/2] Fix "Offset (int|string) might not exist on array" after `array_keys($arr)` --- src/Analyser/NodeScopeResolver.php | 17 +++++++++++++++++ ...NonexistentOffsetInArrayDimFetchRuleTest.php | 7 +++++++ tests/PHPStan/Rules/Arrays/data/bug-12926.php | 13 +++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 tests/PHPStan/Rules/Arrays/data/bug-12926.php diff --git a/src/Analyser/NodeScopeResolver.php b/src/Analyser/NodeScopeResolver.php index c952da2e95..d5f87e3f15 100644 --- a/src/Analyser/NodeScopeResolver.php +++ b/src/Analyser/NodeScopeResolver.php @@ -6521,6 +6521,23 @@ private function enterForeach(MutatingScope $scope, MutatingScope $originalScope } } + if ( + $stmt->expr instanceof FuncCall + && $stmt->expr->name instanceof Name + && $stmt->expr->name->toLowerString() === 'array_keys' + && $stmt->valueVar instanceof Variable + ) { + $args = $stmt->expr->getArgs(); + if (count($args) >= 1) { + $arrayArg = $args[0]->value; + $scope = $scope->assignExpression( + new ArrayDimFetch($arrayArg, $stmt->valueVar), + $scope->getType($arrayArg)->getIterableValueType(), + $scope->getNativeType($arrayArg)->getIterableValueType(), + ); + } + } + return $this->processVarAnnotation($scope, $vars, $stmt); } diff --git a/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php b/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php index 48e9f1012d..6c79bcc795 100644 --- a/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php +++ b/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php @@ -1000,4 +1000,11 @@ public function testBug10492(): void ]); } + public function testBug12926(): void + { + $this->reportPossiblyNonexistentGeneralArrayOffset = true; + + $this->analyse([__DIR__ . '/data/bug-12926.php'], []); + } + } diff --git a/tests/PHPStan/Rules/Arrays/data/bug-12926.php b/tests/PHPStan/Rules/Arrays/data/bug-12926.php new file mode 100644 index 0000000000..b5ffcae460 --- /dev/null +++ b/tests/PHPStan/Rules/Arrays/data/bug-12926.php @@ -0,0 +1,13 @@ + Date: Sun, 28 Sep 2025 11:25:15 +0200 Subject: [PATCH 2/2] Update bug-12926.php --- tests/PHPStan/Rules/Arrays/data/bug-12926.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/PHPStan/Rules/Arrays/data/bug-12926.php b/tests/PHPStan/Rules/Arrays/data/bug-12926.php index b5ffcae460..d83bd21b36 100644 --- a/tests/PHPStan/Rules/Arrays/data/bug-12926.php +++ b/tests/PHPStan/Rules/Arrays/data/bug-12926.php @@ -1,6 +1,6 @@ -