Menu::getChoiceNames()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
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
    const KEY = '';
15
16
    protected function configure()
17
    {
18
        $this
19
            ->setName(static::KEY)
20
            ->setDescription("Menu for {static::KEY} endpoint")
21
            ->setHelp('Some basic menu help');
22
    }
23
    
24
    protected function execute(InputInterface $input, OutputInterface $output)
25
    {
26
        /** @var QuestionHelper $helper $helper */
27
        $helper = $this->getHelper('question');
28
        $question = new ChoiceQuestion(
29
            $this->getQuestion(),
30
            $this->getChoiceNames(),
31
            0
32
        );
33
        $question->setErrorMessage('Action %s is invalid.');
34
        
35
        while (true) {
36
            $choice = $helper->ask($input, $output, $question);
37
            $command = $this->getCommandForChoice($choice);
38
            if ($command === null) {
39
                return 0;
40
            } else {
41
                $command = $this->getApplication()->find($command);
42
                
43
                $command->run(new ArrayInput([]), $output);
44
            }
45
        }
46
        
47
        return 0;
48
    }
49
    
50
    /**
51
     * @return string
52
     */
53
    protected abstract function getQuestion();
54
    
55
    /**
56
     * @return Choice[]
57
     */
58
    protected abstract function getChoices();
59
    
60
    /**
61
     * @return string[]
62
     */
63
    private function getChoiceNames()
64
    {
65
        $names = [];
66
        foreach ($this->getChoices() as $choice) {
67
            $names[] = $choice->getOption();
68
        }
69
        return $names;
70
    }
71
    
72
    private function getCommandForChoice(string $option)
73
    {
74
        foreach ($this->getChoices() as $choice) {
75
            if ($choice->getOption() === $option) {
76
                return $choice->getCommand();
77
            }
78
        }
79
        throw new CommandNotFoundException("Command for $option not found");
80
    }
81
}