-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDisallowEntityArrayAccessRule.php
More file actions
64 lines (57 loc) · 1.64 KB
/
DisallowEntityArrayAccessRule.php
File metadata and controls
64 lines (57 loc) · 1.64 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
<?php
declare(strict_types=1);
namespace CakeDC\PHPStan\Rule\Model;
use Cake\Datasource\EntityInterface;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Scalar\String_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
class DisallowEntityArrayAccessRule implements Rule
{
/**
* @var list<string>
*/
protected array $allowedKeys = [
'_matchingData',
'_joinData',
'_ids',
];
/**
* @inheritDoc
*/
public function getNodeType(): string
{
return ArrayDimFetch::class;
}
/**
* @param \PhpParser\Node $node
* @param \PHPStan\Analyser\Scope $scope
* @return list<\PHPStan\Rules\IdentifierRuleError>
* @throws \PHPStan\ShouldNotHappenException
*/
public function processNode(Node $node, Scope $scope): array
{
assert($node instanceof ArrayDimFetch);
$type = $scope->getType($node->var);
if (!$type->isObject()->yes()) {
return [];
}
$reflection = $type->getObjectClassReflections()[0] ?? null;
if ($reflection === null || !$reflection->is(EntityInterface::class)) {
return [];
}
if ($node->dim instanceof String_ && in_array($node->dim->value, $this->allowedKeys, true)) {
return [];
}
return [
RuleErrorBuilder::message(sprintf(
'Array access to entity %s is not allowed, access as object instead',
$reflection->getName(),
))
->identifier('cake.entity.arrayAccess')
->build(),
];
}
}