Menu   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
wmc 9
lcom 2
cbo 6
dl 0
loc 70
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 7 1
B execute() 0 25 3
getQuestion() 0 1 ?
getChoices() 0 1 ?
A getChoiceNames() 0 8 2
A getCommandForChoice() 0 9 3
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
}