|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\Jack\Console\Command; |
| 6 | + |
| 7 | +use Symfony\Component\Console\Application; |
| 8 | +use Symfony\Component\Console\Command\Command; |
| 9 | +use Symfony\Component\Console\Command\ListCommand; |
| 10 | +use Symfony\Component\Console\Descriptor\ApplicationDescription; |
| 11 | +use Symfony\Component\Console\Input\InputInterface; |
| 12 | +use Symfony\Component\Console\Output\OutputInterface; |
| 13 | +use Webmozart\Assert\Assert; |
| 14 | + |
| 15 | +/** |
| 16 | + * Simple command list, without bloated options |
| 17 | + */ |
| 18 | +final class CleanListCommand extends ListCommand |
| 19 | +{ |
| 20 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 21 | + { |
| 22 | + Assert::isInstanceOf($this->getApplication(), Application::class); |
| 23 | + |
| 24 | + $output->writeln($this->getApplication()->getName()); |
| 25 | + $output->writeln(''); |
| 26 | + $output->writeln('<comment>Available commands:</>'); |
| 27 | + |
| 28 | + $applicationDescription = new ApplicationDescription($this->getApplication()); |
| 29 | + $this->describeCommands($applicationDescription, $output); |
| 30 | + |
| 31 | + return self::SUCCESS; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @param non-empty-array<Command> $commands |
| 36 | + */ |
| 37 | + private function resolveCommandNameColumnWidth(array $commands): int |
| 38 | + { |
| 39 | + $commandNameLengths = []; |
| 40 | + foreach ($commands as $command) { |
| 41 | + $commandNameLengths[] = strlen((string) $command->getName()); |
| 42 | + } |
| 43 | + |
| 44 | + return max($commandNameLengths) + 4; |
| 45 | + } |
| 46 | + |
| 47 | + private function describeCommands(ApplicationDescription $applicationDescription, OutputInterface $output): void |
| 48 | + { |
| 49 | + if ($applicationDescription->getCommands() === []) { |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + $commands = $applicationDescription->getCommands(); |
| 54 | + $commandNameColumnWidth = $this->resolveCommandNameColumnWidth($commands); |
| 55 | + |
| 56 | + foreach ($commands as $command) { |
| 57 | + $spacingWidth = $commandNameColumnWidth - strlen((string) $command->getName()); |
| 58 | + |
| 59 | + $output->writeln(sprintf( |
| 60 | + ' <info>%s</>%s%s', |
| 61 | + $command->getName(), |
| 62 | + str_repeat(' ', $spacingWidth), |
| 63 | + $command->getDescription() |
| 64 | + )); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments