forked from rectorphp/type-perfect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoArrayAccessOnObjectRule.php
More file actions
79 lines (68 loc) · 1.83 KB
/
NoArrayAccessOnObjectRule.php
File metadata and controls
79 lines (68 loc) · 1.83 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace Rector\TypePerfect\Rules;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ObjectType;
/**
* @see \Rector\TypePerfect\Tests\Rules\NoArrayAccessOnObjectRule\NoArrayAccessOnObjectRuleTest
* @implements Rule<ArrayDimFetch>
*/
final class NoArrayAccessOnObjectRule implements Rule
{
/**
* @var string
*/
public const ERROR_MESSAGE = 'Use explicit methods over array access on object';
/**
* @var string[]
*/
private const ALLOWED_CLASSES = [
'SplFixedArray',
'SimpleXMLElement',
'Iterator',
'WeakMap',
'Aws\ResultInterface',
'Symfony\Component\Form\FormInterface',
'Symfony\Component\OptionsResolver\Options',
];
/**
* @return class-string<Node>
*/
public function getNodeType(): string
{
return ArrayDimFetch::class;
}
/**
* @param ArrayDimFetch $node
* @return RuleError[]
*/
public function processNode(Node $node, Scope $scope): array
{
$varType = $scope->getType($node->var);
if (! $varType instanceof ObjectType) {
return [];
}
if ($this->isAllowedObjectType($varType)) {
return [];
}
return [
RuleErrorBuilder::message(self::ERROR_MESSAGE)
->identifier('typePerfect.noArrayAccessOnObject')
->build(),
];
}
private function isAllowedObjectType(ObjectType $objectType): bool
{
foreach (self::ALLOWED_CLASSES as $allowedClass) {
if ($objectType->isInstanceOf($allowedClass)->yes()) {
return true;
}
}
return false;
}
}