Skip to content

Commit 2c7ed0b

Browse files
committed
Fix false positives on non-existing-offsets of super-globals
1 parent 54ca85b commit 2c7ed0b

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

src/Analyser/MutatingScope.php

Lines changed: 5 additions & 1 deletion
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
}

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ private static function findTestFiles(): iterable
209209
yield __DIR__ . '/../Rules/Classes/data/mixin-trait-use.php';
210210

211211
yield __DIR__ . '/../Rules/Methods/data/bug-4801.php';
212+
yield __DIR__ . '/../Rules/Arrays/data/narrow-superglobal.php';
212213
}
213214

214215
/**

tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -856,4 +856,11 @@ public function testBug8649(): void
856856
$this->analyse([__DIR__ . '/data/bug-8649.php'], []);
857857
}
858858

859+
public function testNarrowSuperglobals(): void
860+
{
861+
$this->reportPossiblyNonexistentGeneralArrayOffset = true;
862+
863+
$this->analyse([__DIR__ . '/data/narrow-superglobal.php'], []);
864+
}
865+
859866
}
Lines changed: 16 additions & 0 deletions
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)