1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00

Variables should outlive namespaces (#8779)

Variables in PHP are not namespaced. In other words, namespaces share
the context with the file they are located in.

See https://3v4l.org/2qvrC

Fixes vimeo/psalm#8778
This commit is contained in:
Bruce Weirdan 2022-11-27 11:45:40 -04:00 committed by GitHub
parent 05b8e0eea6
commit 8fa35c2228
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 13 deletions

View File

@ -87,16 +87,17 @@ class NamespaceAnalyzer extends SourceAnalyzer
if ($leftover_stmts) {
$statements_analyzer = new StatementsAnalyzer($this, new NodeDataProvider());
$context = new Context();
$context->is_global = true;
$context->defineGlobals();
$context->collect_exceptions = $codebase->config->check_for_throws_in_global_scope;
$statements_analyzer->analyze($leftover_stmts, $context, null, true);
$file_context = $this->source->context;
if ($file_context) {
$file_context->mergeExceptions($context);
if ($file_context !== null) {
$context = $file_context;
} else {
$context = new Context();
$context->is_global = true;
$context->defineGlobals();
$context->collect_exceptions = $codebase->config->check_for_throws_in_global_scope;
}
$statements_analyzer->analyze($leftover_stmts, $context, null, true);
}
}

View File

@ -152,7 +152,7 @@ class ConfigTest extends TestCase
$config = $this->project_analyzer->getConfig();
$this->assertTrue($config->isInProjectDirs(realpath('src/Psalm/Type.php')));
$this->assertFalse($config->isInProjectDirs(realpath(__DIR__.'/../../').'/does/not/exist/FileAnalyzer.php'));
$this->assertFalse($config->isInProjectDirs(realpath(__DIR__ . '/../../') . '/does/not/exist/FileAnalyzer.php'));
$this->assertFalse($config->isInProjectDirs(realpath('examples/TemplateScanner.php')));
}
@ -1159,15 +1159,18 @@ class ConfigTest extends TestCase
ord($_GET["str"]);
}
$glob1 = 0;
error_reporting($glob1);
$z = $glob1;
$z = 0;
error_reporting($z);
$old = $_GET["str"];
$_GET["str"] = 0;
error_reporting($_GET["str"]);
$_GET["str"] = $old;
function example2(): void {
global $glob1, $glob2, $glob3;
error_reporting($glob1);
global $z, $glob2, $glob3;
error_reporting($z);
ord($glob2["str"]);
$glob3->func();
ord($_GET["str"]);

View File

@ -71,6 +71,24 @@ class NamespaceTest extends TestCase
$c = $argv;
}',
],
'varsAreNotScoped' => [
'code' => '<?php
namespace A {
$a = "1";
}
namespace B\C {
$bc = "2";
}
namespace {
echo $a . PHP_EOL;
echo $bc . PHP_EOL;
}
',
'assertions' => [
'$a===' => "'1'",
'$bc===' => "'2'",
],
],
];
}