-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathUndefinedOptionRule.php
84 lines (71 loc) · 2.28 KB
/
UndefinedOptionRule.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
83
84
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Symfony;
use InvalidArgumentException;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Printer\Printer;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Symfony\ConsoleApplicationResolver;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Symfony\Helper;
use function count;
use function sprintf;
/**
* @implements Rule<MethodCall>
*/
final class UndefinedOptionRule implements Rule
{
private ConsoleApplicationResolver $consoleApplicationResolver;
private Printer $printer;
public function __construct(ConsoleApplicationResolver $consoleApplicationResolver, Printer $printer)
{
$this->consoleApplicationResolver = $consoleApplicationResolver;
$this->printer = $printer;
}
public function getNodeType(): string
{
return MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
$classReflection = $scope->getClassReflection();
if ($classReflection === null) {
return [];
}
if (!(new ObjectType('Symfony\Component\Console\Command\Command'))->isSuperTypeOf(new ObjectType($classReflection->getName()))->yes()) {
return [];
}
if (!(new ObjectType('Symfony\Component\Console\Input\InputInterface'))->isSuperTypeOf($scope->getType($node->var))->yes()) {
return [];
}
if (!$node->name instanceof Node\Identifier || $node->name->name !== 'getOption') {
return [];
}
if (!isset($node->getArgs()[0])) {
return [];
}
$optType = $scope->getType($node->getArgs()[0]->value);
$optStrings = $optType->getConstantStrings();
if (count($optStrings) !== 1) {
return [];
}
$optName = $optStrings[0]->getValue();
$errors = [];
foreach ($this->consoleApplicationResolver->findCommands($classReflection) as $name => $command) {
try {
$command->mergeApplicationDefinition();
$command->getDefinition()->getOption($optName);
} catch (InvalidArgumentException $e) {
if ($scope->getType(Helper::createMarkerNode($node->var, $optType, $this->printer))->equals($optType)) {
continue;
}
$errors[] = RuleErrorBuilder::message(sprintf('Command "%s" does not define option "%s".', $name, $optName))
->identifier('symfonyConsole.optionNotFound')
->build();
}
}
return $errors;
}
}