-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathInvalidKeyInArrayItemRule.php
53 lines (44 loc) · 1.27 KB
/
InvalidKeyInArrayItemRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Arrays;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\MixedType;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<Node\Expr\ArrayItem>
*/
class InvalidKeyInArrayItemRule implements Rule
{
public function __construct(private bool $reportMaybes)
{
}
public function getNodeType(): string
{
return Node\Expr\ArrayItem::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->key === null) {
return [];
}
$dimensionType = $scope->getType($node->key);
$isSuperType = AllowedArrayKeysTypes::getType()->isSuperTypeOf($dimensionType);
if ($isSuperType->no()) {
return [
RuleErrorBuilder::message(
sprintf('Invalid array key type %s.', $dimensionType->describe(VerbosityLevel::typeOnly())),
)->identifier('array.invalidKey')->build(),
];
} elseif ($this->reportMaybes && $isSuperType->maybe() && !$dimensionType instanceof MixedType) {
return [
RuleErrorBuilder::message(
sprintf('Possibly invalid array key type %s.', $dimensionType->describe(VerbosityLevel::typeOnly())),
)->identifier('array.invalidKey')->build(),
];
}
return [];
}
}