Skip to content

Commit c8833df

Browse files
authored
Fix false positives on non-existing offsets of superglobals
1 parent 39c65a9 commit c8833df

File tree

4 files changed

+27
-4
lines changed

4 files changed

+27
-4
lines changed

src/Analyser/MutatingScope.php

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

551-
if ($this->isGlobalVariable($variableName)) {
552-
return new ArrayType(new BenevolentUnionType([new IntegerType(), new StringType()]), new MixedType(true));
553-
}
554-
555551
if ($this->hasVariableType($variableName)->no()) {
556552
throw new UndefinedVariableException($this, $variableName);
557553
}
558554

559555
$varExprString = '$' . $variableName;
560556
if (!array_key_exists($varExprString, $this->expressionTypes)) {
557+
if ($this->isGlobalVariable($variableName)) {
558+
return new ArrayType(new BenevolentUnionType([new IntegerType(), new StringType()]), new MixedType(true));
559+
}
561560
return new MixedType();
562561
}
563562

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
/**

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
}
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)