-
Notifications
You must be signed in to change notification settings - Fork 3
/
DisallowEnvironmentCheckRule.php
108 lines (86 loc) · 2.83 KB
/
DisallowEnvironmentCheckRule.php
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
declare(strict_types=1);
namespace Worksome\CodingStyle\PHPStan\Laravel\DisallowEnvironmentCheck;
use PhpParser\Node;
use PhpParser\Node\Expr\CallLike;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ObjectType;
final class DisallowEnvironmentCheckRule implements Rule
{
private const METHOD_NAME = 'environment';
public function getNodeType(): string
{
return CallLike::class;
}
/**
* @param CallLike $node
*
* @return array<RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
if (! $node instanceof MethodCall && ! $node instanceof StaticCall) {
return [];
}
if (! $node->name instanceof Node\Identifier) {
return [];
}
if ($node->name->toLowerString() !== self::METHOD_NAME) {
return [];
}
return match ($node::class) {
Node\Expr\MethodCall::class => $this->checkMethodCall($node->var, $scope),
Node\Expr\StaticCall::class => $this->checkFacade($node->class),
default => [],
};
}
private function checkMethodCall(Node\Expr $node, Scope $scope): array
{
if ($node instanceof Node\Expr\FuncCall) {
return $this->checkGlobalAppHelper($node);
}
if ($node instanceof Node\Expr\Variable) {
return $this->checkAppVariable($node, $scope);
}
return [];
}
private function checkGlobalAppHelper(Node\Expr\FuncCall $node): array
{
return $node->name->toLowerString() === 'app' ? [$this->error()] : [];
}
private function checkAppVariable(Node\Expr\Variable $node, Scope $scope): array
{
$nativeType = $scope->getNativeType($node);
if (! $nativeType instanceof ObjectType) {
return [];
}
if ($nativeType->getClassName() === 'Illuminate\Contracts\Foundation\Application') {
return [$this->error()];
}
if ($nativeType->getClassName() === 'Illuminate\Foundation\Application') {
return [$this->error()];
}
return [];
}
private function checkFacade(Node\Name|Node\Expr $var): array
{
if (! $var instanceof Node\Name) {
return [];
}
if (in_array($var->toCodeString(), ['\Illuminate\Support\Facades\App', '\App'])) {
return [$this->error()];
}
return [];
}
private function error(): RuleError
{
return RuleErrorBuilder::message('Environment checks are disallowed. Please use the driver pattern instead.')
->identifier('worksome.laravel.disallowEnvironmentCheck')
->build();
}
}