diff --git a/src/Psalm/Context.php b/src/Psalm/Context.php index 1101b8fe555..7531fcbd4a8 100644 --- a/src/Psalm/Context.php +++ b/src/Psalm/Context.php @@ -367,6 +367,11 @@ class Context */ public $has_returned = false; + /** + * @var array + */ + public $vars_from_global = []; + public function __construct(?string $self = null) { $this->self = $self; diff --git a/src/Psalm/Internal/Analyzer/Statements/GlobalAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/GlobalAnalyzer.php index dc27c13ae0e..6ebb3d34beb 100644 --- a/src/Psalm/Internal/Analyzer/Statements/GlobalAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/GlobalAnalyzer.php @@ -65,6 +65,7 @@ public static function analyze( $context->vars_in_scope[$var_id]->parent_nodes = [ $assignment_node->id => $assignment_node, ]; + $context->vars_from_global[$var_id] = true; $statements_analyzer->registerVariable( $var_id, new CodeLocation($statements_analyzer, $var), diff --git a/src/Psalm/Internal/Analyzer/StatementsAnalyzer.php b/src/Psalm/Internal/Analyzer/StatementsAnalyzer.php index fd154f7a663..034ee5baefd 100644 --- a/src/Psalm/Internal/Analyzer/StatementsAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/StatementsAnalyzer.php @@ -194,7 +194,7 @@ public function analyze( && $context->check_variables ) { //var_dump($this->data_flow_graph); - $this->checkUnreferencedVars($stmts); + $this->checkUnreferencedVars($stmts, $context); } if ($codebase->alter_code && $root_scope && $this->vars_to_initialize) { @@ -701,7 +701,7 @@ private function parseStatementDocblock( /** * @param array $stmts */ - public function checkUnreferencedVars(array $stmts): void + public function checkUnreferencedVars(array $stmts, Context $context): void { $source = $this->getSource(); $codebase = $source->getCodebase(); @@ -776,6 +776,7 @@ public function checkUnreferencedVars(array $stmts): void $assignment_node = DataFlowNode::getForAssignment($var_id, $original_location); if (!isset($this->byref_uses[$var_id]) + && !isset($context->vars_from_global[$var_id]) && !VariableFetchAnalyzer::isSuperGlobal($var_id) && $this->data_flow_graph instanceof VariableUseGraph && !$this->data_flow_graph->isVariableUsed($assignment_node) diff --git a/tests/UnusedVariableTest.php b/tests/UnusedVariableTest.php index 6e4790a2b81..f9235c698b3 100644 --- a/tests/UnusedVariableTest.php +++ b/tests/UnusedVariableTest.php @@ -2424,6 +2424,14 @@ function randomBits() : string return $randomBytes; }' ], + 'globalChangeValue' => [ + ' 'UnusedVariable', ], - 'globalVariableUsage' => [ - ' 'UnusedVariable', - ], 'warnAboutOriginalBadArray' => [ '