-
Notifications
You must be signed in to change notification settings - Fork 435
/
ArrayUnpackingRule.php
67 lines (56 loc) · 1.58 KB
/
ArrayUnpackingRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Arrays;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayItem;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Expr\GetIterableKeyTypeExpr;
use PHPStan\Php\PhpVersion;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\ErrorType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<ArrayItem>
*/
class ArrayUnpackingRule implements Rule
{
public function __construct(private PhpVersion $phpVersion, private RuleLevelHelper $ruleLevelHelper)
{
}
public function getNodeType(): string
{
return ArrayItem::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->unpack === false || $this->phpVersion->supportsArrayUnpackingWithStringKeys()) {
return [];
}
$stringType = new StringType();
$typeResult = $this->ruleLevelHelper->findTypeToCheck(
$scope,
new GetIterableKeyTypeExpr($node->value),
'',
static fn (Type $type): bool => $stringType->isSuperTypeOf($type)->no(),
);
$keyType = $typeResult->getType();
if ($keyType instanceof ErrorType) {
return $typeResult->getUnknownClassErrors();
}
$isString = $stringType->isSuperTypeOf($keyType);
if ($isString->no()) {
return [];
}
return [
RuleErrorBuilder::message(sprintf(
'Array unpacking cannot be used on an array with %sstring keys: %s',
$isString->yes() ? '' : 'potential ',
$scope->getType($node->value)->describe(VerbosityLevel::value()),
))->build(),
];
}
}