Skip to content

Commit

Permalink
static and global cannot be used in pure context
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Apr 3, 2024
1 parent d303c60 commit f659df5
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Analyser/ImpurePoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use PHPStan\Node\VirtualNode;

/**
* @phpstan-type ImpurePointIdentifier = 'echo'|'die'|'exit'|'propertyAssign'|'methodCall'|'new'|'functionCall'|'include'|'require'|'print'|'eval'|'superglobal'|'yield'|'yieldFrom'
* @phpstan-type ImpurePointIdentifier = 'echo'|'die'|'exit'|'propertyAssign'|'methodCall'|'new'|'functionCall'|'include'|'require'|'print'|'eval'|'superglobal'|'yield'|'yieldFrom'|'static'|'global'
* @api
*/
class ImpurePoint
Expand Down
20 changes: 18 additions & 2 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1691,7 +1691,15 @@ static function (Node $node, Scope $scope) use ($nodeCallback): void {
} elseif ($stmt instanceof Node\Stmt\Global_) {
$hasYield = false;
$throwPoints = [];
$impurePoints = [];
$impurePoints = [
new ImpurePoint(
$scope,
$stmt,
'global',
'global variable',
true,
),
];
$vars = [];
foreach ($stmt->vars as $var) {
if (!$var instanceof Variable) {
Expand All @@ -1713,7 +1721,15 @@ static function (Node $node, Scope $scope) use ($nodeCallback): void {
} elseif ($stmt instanceof Static_) {
$hasYield = false;
$throwPoints = [];
$impurePoints = [];
$impurePoints = [
new ImpurePoint(
$scope,
$stmt,
'static',
'static variable',
true,
),
];

$vars = [];
foreach ($stmt->vars as $var) {
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Pure/PureFunctionRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ public function testRule(): void
'Impure access to superglobal variable in pure function PureFunction\pureButAccessSuperGlobal().',
104,
],
[
'Impure global variable in pure function PureFunction\functionWithGlobal().',
117,
],
[
'Impure static variable in pure function PureFunction\functionWithStaticVariable().',
127,
],
]);
}

Expand Down
20 changes: 20 additions & 0 deletions tests/PHPStan/Rules/Pure/data/pure-function.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,23 @@ function emptyVoidFunctionWithByRefParameter(&$a): void
{

}

/**
* @phpstan-pure
*/
function functionWithGlobal(): int
{
global $db;

return 1;
}

/**
* @phpstan-pure
*/
function functionWithStaticVariable(): int
{
static $v = 1;

return $v;
}

0 comments on commit f659df5

Please sign in to comment.