1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-21 21:31:13 +01:00

Fix #2696 - make sure static property references are prevented in pure functions

This commit is contained in:
Matthew Brown 2020-01-27 22:55:20 -05:00
parent 5f7730c12e
commit 5c3ec7a531
5 changed files with 66 additions and 0 deletions

View File

@ -184,6 +184,7 @@
<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="ImpureStaticProperty" 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

@ -428,6 +428,23 @@ function addCumulative(int $left) : int {
}
```
### ImpureStaticProperty
Emitted when attempting to use a static property from a function or method marked as pure
```php
class ValueHolder {
public static ?string $value = null;
/**
* @psalm-pure
*/
public static function get(): ?string {
return self::$value;
}
}
```
### InaccessibleClassConstant
Emitted when a public/private class constant is not accessible from the calling context

View File

@ -1084,6 +1084,18 @@ class PropertyFetchAnalyzer
);
}
if ($context->mutation_free) {
if (IssueBuffer::accepts(
new \Psalm\Issue\ImpureStaticProperty(
'Cannot use a static property in a mutation-free context',
new CodeLocation($statements_analyzer, $stmt)
),
$statements_analyzer->getSuppressedIssues()
)) {
// fall through
}
}
if ($var_id && $context->hasVariable($var_id, $statements_analyzer)) {
$stmt_type = $context->vars_in_scope[$var_id];

View File

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

View File

@ -353,6 +353,36 @@ class PureAnnotationTest extends TestCase
}',
'error_message' => 'ImpureByReferenceAssignment'
],
'staticPropertyFetch' => [
'<?php
final class Number1 {
public static ?string $zero = null;
/**
* @psalm-pure
*/
public static function zero(): ?string {
return self::$zero;
}
}',
'error_message' => 'ImpureStaticProperty',
],
'staticPropertyAssignment' => [
'<?php
final class Number1 {
/** @var string|null */
private static $zero;
/**
* @psalm-pure
*/
public static function zero(): string {
self::$zero = "Zero";
return "hello";
}
}',
'error_message' => 'ImpureStaticProperty',
],
];
}
}