tarlepp /
symfony-flex-backend
| 1 | <?php |
||
| 2 | declare(strict_types = 1); |
||
| 3 | /** |
||
| 4 | * /src/Command/Traits/ExecuteMultipleCommandTrait.php |
||
| 5 | * |
||
| 6 | * @author TLe, Tarmo Leppänen <[email protected]> |
||
| 7 | */ |
||
| 8 | |||
| 9 | namespace App\Command\Traits; |
||
| 10 | |||
| 11 | use Symfony\Component\Console\Input\ArrayInput; |
||
| 12 | use Symfony\Component\Console\Input\InputInterface; |
||
| 13 | use Symfony\Component\Console\Output\OutputInterface; |
||
| 14 | use Symfony\Component\Console\Style\SymfonyStyle; |
||
| 15 | use Throwable; |
||
| 16 | use function array_flip; |
||
| 17 | use function array_search; |
||
| 18 | use function array_values; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Trait ExecuteMultipleCommandTrait |
||
| 22 | * |
||
| 23 | * @package App\Command\Traits |
||
| 24 | * @author TLe, Tarmo Leppänen <[email protected]> |
||
| 25 | */ |
||
| 26 | trait ExecuteMultipleCommandTrait |
||
| 27 | { |
||
| 28 | use GetApplicationTrait; |
||
| 29 | use SymfonyStyleTrait; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @var array<array-key, string> |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 33 | */ |
||
| 34 | private array $choices = []; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Setter method for choices to use. |
||
| 38 | * |
||
| 39 | * @param array<array-key, string> $choices |
||
|
0 ignored issues
–
show
|
|||
| 40 | */ |
||
| 41 | protected function setChoices(array $choices): void |
||
| 42 | { |
||
| 43 | $this->choices = $choices; |
||
| 44 | } |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @throws Throwable |
||
| 48 | */ |
||
| 49 | protected function execute(InputInterface $input, OutputInterface $output): int |
||
| 50 | { |
||
| 51 | $io = $this->getSymfonyStyle($input, $output); |
||
| 52 | $command = $this->ask($io); |
||
| 53 | |||
| 54 | while ($command !== null) { |
||
| 55 | $arguments = [ |
||
| 56 | 'command' => $command, |
||
| 57 | ]; |
||
| 58 | |||
| 59 | $input = new ArrayInput($arguments); |
||
| 60 | |||
| 61 | $cmd = $this->getApplication()->find($command); |
||
| 62 | $outputValue = $cmd->run($input, $output); |
||
| 63 | |||
| 64 | $command = $this->ask($io); |
||
| 65 | } |
||
| 66 | |||
| 67 | if ($input->isInteractive()) { |
||
| 68 | $io->success('Have a nice day'); |
||
| 69 | } |
||
| 70 | |||
| 71 | return $outputValue ?? 0; |
||
| 72 | } |
||
| 73 | |||
| 74 | /** |
||
| 75 | * Method to ask user to make choose one of defined choices. |
||
| 76 | */ |
||
| 77 | private function ask(SymfonyStyle $io): ?string |
||
| 78 | { |
||
| 79 | $index = array_search( |
||
| 80 | $io->choice('What you want to do', array_values($this->choices)), |
||
| 81 | array_values($this->choices), |
||
| 82 | true, |
||
| 83 | ); |
||
| 84 | |||
| 85 | $choice = (string)array_values(array_flip($this->choices))[(int)$index]; |
||
| 86 | |||
| 87 | return $choice === '0' ? null : $choice; |
||
| 88 | } |
||
| 89 | } |
||
| 90 |