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

Detect use of static inside pure function

This commit is contained in:
Matthew Brown 2019-08-31 21:31:53 -04:00
parent dcc4de59df
commit dee2cf3281
5 changed files with 44 additions and 0 deletions

View File

@ -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" />

View File

@ -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

View File

@ -1296,6 +1296,18 @@ class StatementsAnalyzer extends SourceAnalyzer implements StatementsSource
{
$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;

View File

@ -0,0 +1,6 @@
<?php
namespace Psalm\Issue;
class ImpureStaticVariable extends CodeIssue
{
}

View File

@ -245,6 +245,17 @@ class PureAnnotationTest extends TestCase
}',
'error_message' => 'ImpureMethodCall',
],
'useOfStaticMakesFunctionImpure' => [
'<?php
/** @psalm-pure */
function addCumulative(int $left) : int {
/** @var int */
static $i = 0;
$i += $left;
return $left;
}',
'error_message' => 'ImpureStaticVariable',
],
];
}
}