-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathConsoleApplicationResolver.php
90 lines (71 loc) · 2.45 KB
/
ConsoleApplicationResolver.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
85
86
87
88
89
90
<?php declare(strict_types = 1);
namespace PHPStan\Symfony;
use PHPStan\Reflection\ClassReflection;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ObjectType;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use function file_exists;
use function get_class;
use function is_readable;
use function method_exists;
use function sprintf;
final class ConsoleApplicationResolver
{
private ?string $consoleApplicationLoader = null;
private ?Application $consoleApplication = null;
public function __construct(?string $consoleApplicationLoader)
{
$this->consoleApplicationLoader = $consoleApplicationLoader;
}
public function hasConsoleApplicationLoader(): bool
{
return $this->consoleApplicationLoader !== null;
}
private function getConsoleApplication(): ?Application
{
if ($this->consoleApplicationLoader === null) {
return null;
}
if ($this->consoleApplication !== null) {
return $this->consoleApplication;
}
if (!file_exists($this->consoleApplicationLoader)
|| !is_readable($this->consoleApplicationLoader)
) {
throw new ShouldNotHappenException(sprintf('Cannot load console application. Check the parameters.symfony.consoleApplicationLoader setting in PHPStan\'s config. The offending value is "%s".', $this->consoleApplicationLoader));
}
return $this->consoleApplication = require $this->consoleApplicationLoader;
}
/**
* @return Command[]
*/
public function findCommands(ClassReflection $classReflection): array
{
$consoleApplication = $this->getConsoleApplication();
if ($consoleApplication === null) {
return [];
}
$classType = new ObjectType($classReflection->getName());
if (!(new ObjectType('Symfony\Component\Console\Command\Command'))->isSuperTypeOf($classType)->yes()) {
return [];
}
$commands = [];
foreach ($consoleApplication->all() as $name => $command) {
$commandClass = new ObjectType(get_class($command));
$isLazyCommand = (new ObjectType('Symfony\Component\Console\Command\LazyCommand'))->isSuperTypeOf($commandClass)->yes();
if ($isLazyCommand && method_exists($command, 'getCommand')) {
/** @var Command $wrappedCommand */
$wrappedCommand = $command->getCommand();
if (!$classType->isSuperTypeOf(new ObjectType(get_class($wrappedCommand)))->yes()) {
continue;
}
}
if (!$isLazyCommand && !$classType->isSuperTypeOf($commandClass)->yes()) {
continue;
}
$commands[$name] = $command;
}
return $commands;
}
}