|
14 | 14 | use Nette\Schema\Expect; |
15 | 15 | use Nette\Schema\Schema; |
16 | 16 | use Nette\Utils\Arrays; |
| 17 | +use ReflectionClass; |
| 18 | +use ReflectionProperty; |
17 | 19 | use stdClass; |
| 20 | +use Symfony\Component\Console\Attribute\AsCommand; |
18 | 21 | use Symfony\Component\Console\Command\Command; |
19 | 22 | use Symfony\Component\Console\CommandLoader\CommandLoaderInterface; |
20 | 23 | use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
|
25 | 28 | class ConsoleExtension extends CompilerExtension |
26 | 29 | { |
27 | 30 |
|
28 | | - private bool $cliMode; |
29 | | - |
30 | | - public function __construct(bool $cliMode = false) |
| 31 | + public function __construct( |
| 32 | + private readonly bool $cliMode = false, |
| 33 | + ) |
31 | 34 | { |
32 | | - $this->cliMode = $cliMode; |
33 | 35 | } |
34 | 36 |
|
35 | 37 | public function getConfigSchema(): Schema |
@@ -158,17 +160,31 @@ public function beforeCompile(): void |
158 | 160 | } |
159 | 161 |
|
160 | 162 | $aliases = []; |
161 | | - // Try to detect command name from Command::getDefaultName() |
162 | | - if ($commandName === null) { |
163 | | - $commandName = call_user_func([$service->getType(), 'getDefaultName']); // @phpstan-ignore-line |
164 | | - if ($commandName === null) { |
| 163 | + // Try to detect command name from Command::getDefaultName() or Command::defaultName property |
| 164 | + if (!is_string($commandName) || $commandName === '') { |
| 165 | + /** @var class-string $className */ |
| 166 | + $className = $service->getType(); |
| 167 | + $reflection = new ReflectionClass($className); |
| 168 | + $attributes = $reflection->getAttributes(AsCommand::class); |
| 169 | + |
| 170 | + if ($attributes !== []) { |
| 171 | + $commandName = $attributes[0]->newInstance()->name; |
| 172 | + } elseif (method_exists($className, 'getDefaultName')) { |
| 173 | + $commandName = call_user_func([$service->getType(), 'getDefaultName']); // @phpstan-ignore-line |
| 174 | + } elseif (property_exists($className, 'defaultName')) { |
| 175 | + $rp = new ReflectionProperty($className, 'defaultName'); |
| 176 | + $commandName = $rp->getValue(); |
| 177 | + } |
| 178 | + |
| 179 | + if (!is_string($commandName) || $commandName === '') { |
165 | 180 | throw new ServiceCreationException( |
166 | 181 | sprintf( |
167 | 182 | 'Command "%s" missing #[AsCommand] attribute', |
168 | 183 | $service->getType(), |
169 | 184 | ) |
170 | 185 | ); |
171 | 186 | } |
| 187 | + |
172 | 188 | $aliases = explode('|', $commandName); |
173 | 189 | $commandName = array_shift($aliases); |
174 | 190 | if ($commandName === '') { |
|
0 commit comments