-
Notifications
You must be signed in to change notification settings - Fork 570
Expand file tree
/
Copy pathNullCoalesceRule.php
More file actions
60 lines (48 loc) · 1.38 KB
/
NullCoalesceRule.php
File metadata and controls
60 lines (48 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Variables;
use PhpParser\Node;
use PHPStan\Analyser\CollectedDataEmitter;
use PHPStan\Analyser\NodeCallbackInvoker;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\IssetCheck;
use PHPStan\Rules\Rule;
use PHPStan\Type\Type;
/**
* @implements Rule<Node\Expr>
*/
#[RegisteredRule(level: 1)]
final class NullCoalesceRule implements Rule
{
public function __construct(private IssetCheck $issetCheck)
{
}
public function getNodeType(): string
{
return Node\Expr::class;
}
public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array
{
$typeMessageCallback = static function (Type $type): ?string {
$isNull = $type->isNull();
if ($isNull->maybe()) {
return null;
}
if ($isNull->yes()) {
return 'is always null';
}
return 'is not nullable';
};
if ($node instanceof Node\Expr\BinaryOp\Coalesce) {
$error = $this->issetCheck->check($node->left, $scope, 'on left side of ??', 'nullCoalesce', $typeMessageCallback, self::class);
} elseif ($node instanceof Node\Expr\AssignOp\Coalesce) {
$error = $this->issetCheck->check($node->var, $scope, 'on left side of ??=', 'nullCoalesce', $typeMessageCallback, self::class);
} else {
return [];
}
if ($error === null) {
return [];
}
return [$error];
}
}