1
|
|
|
<?php |
2
|
|
|
namespace BarenoteCli\Command\Menu; |
3
|
|
|
|
4
|
|
|
use Symfony\Component\Console\Command\Command; |
5
|
|
|
use Symfony\Component\Console\Exception\CommandNotFoundException; |
6
|
|
|
use Symfony\Component\Console\Helper\QuestionHelper; |
7
|
|
|
use Symfony\Component\Console\Input\ArrayInput; |
8
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
9
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
10
|
|
|
use Symfony\Component\Console\Question\ChoiceQuestion; |
11
|
|
|
|
12
|
|
|
abstract class Menu extends Command |
13
|
|
|
{ |
14
|
|
|
protected function configure() |
15
|
|
|
{ |
16
|
|
|
$this |
17
|
|
|
->setName("barenote:{$this->getSlug()}:menu") |
|
|
|
|
18
|
|
|
->setDescription("Menu for {$this->getSlug()} endpoint") |
|
|
|
|
19
|
|
|
->setHelp('Some basic menu help'); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
protected function execute(InputInterface $input, OutputInterface $output) |
23
|
|
|
{ |
24
|
|
|
/** @var QuestionHelper $helper $helper */ |
25
|
|
|
$helper = $this->getHelper('question'); |
26
|
|
|
$question = new ChoiceQuestion( |
27
|
|
|
$this->getQuestion(), |
28
|
|
|
$this->getChoiceNames(), |
29
|
|
|
0 |
30
|
|
|
); |
31
|
|
|
$question->setErrorMessage('Action %s is invalid.'); |
32
|
|
|
|
33
|
|
|
while (true) { |
34
|
|
|
$choice = $helper->ask($input, $output, $question); |
35
|
|
|
$command = $this->getCommandForChoice($choice); |
36
|
|
|
if ($command === null) { |
37
|
|
|
return 0; |
38
|
|
|
} else { |
39
|
|
|
$command = $this->getApplication()->find($command); |
40
|
|
|
|
41
|
|
|
$command->run(new ArrayInput([]), $output); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return 0; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return string |
50
|
|
|
*/ |
51
|
|
|
protected abstract function getSlug(); |
|
|
|
|
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
protected abstract function getQuestion(); |
|
|
|
|
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return Choice[] |
60
|
|
|
*/ |
61
|
|
|
protected abstract function getChoices(); |
|
|
|
|
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @return string[] |
65
|
|
|
*/ |
66
|
|
|
private function getChoiceNames() |
67
|
|
|
{ |
68
|
|
|
$names = []; |
69
|
|
|
foreach ($this->getChoices() as $choice) { |
70
|
|
|
$names[] = $choice->getOption(); |
71
|
|
|
} |
72
|
|
|
return $names; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function getCommandForChoice(string $option) |
76
|
|
|
{ |
77
|
|
|
foreach ($this->getChoices() as $choice) { |
78
|
|
|
if ($choice->getOption() === $option) { |
79
|
|
|
return $choice->getCommand(); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
throw new CommandNotFoundException("Command for $option not found"); |
|
|
|
|
83
|
|
|
} |
84
|
|
|
} |
It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.