-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathInvalidArgumentDefaultValueRule.php
82 lines (71 loc) · 2.41 KB
/
InvalidArgumentDefaultValueRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Symfony;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StringType;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;
use function count;
use function sprintf;
/**
* @implements Rule<MethodCall>
*/
final class InvalidArgumentDefaultValueRule implements Rule
{
public function getNodeType(): string
{
return MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!(new ObjectType('Symfony\Component\Console\Command\Command'))->isSuperTypeOf($scope->getType($node->var))->yes()) {
return [];
}
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'addArgument') {
return [];
}
if (!isset($node->getArgs()[3])) {
return [];
}
$modeType = isset($node->getArgs()[1]) ? $scope->getType($node->getArgs()[1]->value) : new NullType();
if ($modeType->isNull()->yes()) {
$modeType = new ConstantIntegerType(2); // InputArgument::OPTIONAL
}
$modeTypes = $modeType->getConstantScalarTypes();
if (count($modeTypes) !== 1) {
return [];
}
if (!$modeTypes[0] instanceof ConstantIntegerType) {
return [];
}
$mode = $modeTypes[0]->getValue();
$defaultType = $scope->getType($node->getArgs()[3]->value);
// not an array
if (($mode & 4) !== 4 && !(new UnionType([new StringType(), new NullType()]))->isSuperTypeOf($defaultType)->yes()) {
return [
RuleErrorBuilder::message(sprintf(
'Parameter #4 $default of method Symfony\Component\Console\Command\Command::addArgument() expects string|null, %s given.',
$defaultType->describe(VerbosityLevel::typeOnly()),
))->identifier('argument.type')->build(),
];
}
// is array
if (($mode & 4) === 4 && !(new UnionType([new ArrayType(new IntegerType(), new StringType()), new NullType()]))->isSuperTypeOf($defaultType)->yes()) {
return [
RuleErrorBuilder::message(sprintf(
'Parameter #4 $default of method Symfony\Component\Console\Command\Command::addArgument() expects array<int, string>|null, %s given.',
$defaultType->describe(VerbosityLevel::typeOnly()),
))->identifier('argument.type')->build(),
];
}
return [];
}
}