Skip to content

Commit 3266a0e

Browse files
committed
Fix false positives on non-existing-offsets of super-globals
1 parent 39c65a9 commit 3266a0e

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

Diff for: src/Analyser/MutatingScope.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -548,15 +548,19 @@ public function getVariableType(string $variableName): Type
548548
}
549549
}
550550

551+
$varExprString = '$' . $variableName;
551552
if ($this->isGlobalVariable($variableName)) {
553+
if (array_key_exists($varExprString, $this->expressionTypes)) {
554+
return TypeUtils::resolveLateResolvableTypes($this->expressionTypes[$varExprString]->getType());
555+
}
556+
552557
return new ArrayType(new BenevolentUnionType([new IntegerType(), new StringType()]), new MixedType(true));
553558
}
554559

555560
if ($this->hasVariableType($variableName)->no()) {
556561
throw new UndefinedVariableException($this, $variableName);
557562
}
558563

559-
$varExprString = '$' . $variableName;
560564
if (!array_key_exists($varExprString, $this->expressionTypes)) {
561565
return new MixedType();
562566
}

Diff for: tests/PHPStan/Analyser/NodeScopeResolverTest.php

+1
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ private static function findTestFiles(): iterable
210210

211211
yield __DIR__ . '/../Rules/Arrays/data/bug-11679.php';
212212
yield __DIR__ . '/../Rules/Methods/data/bug-4801.php';
213+
yield __DIR__ . '/../Rules/Arrays/data/narrow-superglobal.php';
213214
}
214215

215216
/**

Diff for: tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php

+7
Original file line numberDiff line numberDiff line change
@@ -870,4 +870,11 @@ public function testBug8649(): void
870870
$this->analyse([__DIR__ . '/data/bug-8649.php'], []);
871871
}
872872

873+
public function testNarrowSuperglobals(): void
874+
{
875+
$this->reportPossiblyNonexistentGeneralArrayOffset = true;
876+
877+
$this->analyse([__DIR__ . '/data/narrow-superglobal.php'], []);
878+
}
879+
873880
}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace NarrowsSuperGlobal;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class HelloWorld
8+
{
9+
public function doFoo(): void
10+
{
11+
if (array_key_exists('HTTP_HOST', $_SERVER)) {
12+
assertType("non-empty-array&hasOffset('HTTP_HOST')", $_SERVER);
13+
echo $_SERVER['HTTP_HOST'];
14+
}
15+
}
16+
}

0 commit comments

Comments
 (0)