Skip to content
Permalink
Browse files

Detect use of static inside pure function

  • Loading branch information...
muglug committed Sep 1, 2019
1 parent dcc4de5 commit dee2cf3281b73efa8710679c966584aeee7a1f5e
@@ -172,6 +172,7 @@
<xs:element name="ImpureFunctionCall" type="IssueHandlerType" minOccurs="0" />
<xs:element name="ImpureMethodCall" type="IssueHandlerType" minOccurs="0" />
<xs:element name="ImpurePropertyAssignment" type="IssueHandlerType" minOccurs="0" />
<xs:element name="ImpureStaticVariable" type="IssueHandlerType" minOccurs="0" />
<xs:element name="InaccessibleClassConstant" type="IssueHandlerType" minOccurs="0" />
<xs:element name="InaccessibleMethod" type="MethodIssueHandlerType" minOccurs="0" />
<xs:element name="InaccessibleProperty" type="IssueHandlerType" minOccurs="0" />
@@ -400,6 +400,20 @@ function filterOdd(int $i, A $a) : ?int {
}
```

### ImpureStaticVariable

Emitted when attempting to use a static variable from a function or method marked as pure

```php
/** @psalm-pure */
function addCumulative(int $left) : int {
/** @var int */
static $i = 0;
$i += $left;
return $left;
}
```

### InaccessibleClassConstant

Emitted when a public/private class constant is not accessible from the calling context
@@ -1296,6 +1296,18 @@ private function analyzeStatic(PhpParser\Node\Stmt\Static_ $stmt, Context $conte
{
$codebase = $this->getCodebase();
if ($context->mutation_free) {
if (IssueBuffer::accepts(
new \Psalm\Issue\ImpureStaticVariable(
'Cannot use a static variable in a mutation-free context',
new CodeLocation($this, $stmt)
),
$this->getSuppressedIssues()
)) {
// fall through
}
}
foreach ($stmt->vars as $var) {
if (!is_string($var->var->name)) {
continue;
@@ -0,0 +1,6 @@
<?php
namespace Psalm\Issue;
class ImpureStaticVariable extends CodeIssue
{
}
@@ -245,6 +245,17 @@ function makesACounter(int $i) : Counter {
}',
'error_message' => 'ImpureMethodCall',
],
'useOfStaticMakesFunctionImpure' => [
'<?php
/** @psalm-pure */
function addCumulative(int $left) : int {
/** @var int */
static $i = 0;
$i += $left;
return $left;
}',
'error_message' => 'ImpureStaticVariable',
],
];
}
}

0 comments on commit dee2cf3

Please sign in to comment.
You can’t perform that action at this time.