App::parseSubcommand()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace Stefaminator\Cli;
5
6
7
use Exception;
8
use GetOptionKit\ContinuousOptionParser;
9
use GetOptionKit\OptionResult;
10
11
abstract class App {
12
13
    /**
14
     * @return Cmd
15
     */
16
    abstract public function setup(): Cmd;
17
18 6
    public function run(): void {
19 6
        global $argv;
20
21
        try {
22 6
            $runner = $this->parse($argv);
23
24 6
            if ($runner !== null) {
25
26 6
                if ($runner->handleOptionParseException()) {
27 1
                    return;
28
                }
29
30 5
                $runner->run();
31
32
            }
33 1
        } catch (Exception $e) {
34
35 1
            Cmd::eol();
36 1
            Cmd::echo('Uups, someting went wrong!', Color::FOREGROUND_COLOR_RED);
37 1
            Cmd::eol();
38 1
            Cmd::echo($e->getMessage(), Color::FOREGROUND_COLOR_RED);
39 1
            Cmd::eol();
40
        }
41
42 5
    }
43
44
    /**
45
     * @param array $argv
46
     * @return Cmd
47
     */
48 22
    public function parse(array $argv): Cmd {
49
50 22
        $runner = $this->setup();
51
52 22
        $appspecs = $runner->optionCollection();
53
54 22
        $parser = new ContinuousOptionParser($appspecs);
55
56
        try {
57 22
            $runner->optionResult = $parser->parse($argv);
58
59 1
        } catch (Exception $e) {
60
61 1
            $runner->optionParseException = $e;
62
63 1
            return $runner;
64
        }
65
66 21
        while (!$parser->isEnd()) {
67
68 17
            $currentArgument = $parser->getCurrentArgument();
69
70 17
            $subcommand = $runner->getChild($currentArgument);
71
72 17
            if ($subcommand !== null) {
73
74 11
                $runner = $subcommand;
75
76
                try {
77 11
                    $this->parseSubcommand($parser, $runner);
78 1
                } catch (Exception $e) {
79 1
                    $runner->optionParseException = $e;
80 11
                    return $runner;
81
                }
82
83
            } else {
84 8
                $runner->arguments[] = $parser->advance();
85
            }
86
        }
87
88 20
        return $runner;
89
    }
90
91
    /**
92
     * @param ContinuousOptionParser $parser
93
     * @param Cmd $runner
94
     */
95 11
    private function parseSubcommand(ContinuousOptionParser $parser, Cmd $runner): void {
96
97 11
        $parser->advance();
98
99 11
        $runner->optionResult = new OptionResult();
100
101 11
        $specs = $runner->optionCollection();
102
103 11
        $parser->setSpecs($specs);
104
105 11
        $runner->optionResult = $parser->continueParse();
106
    }
107
}