Handler::parseInput()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace Parking\Console;
3
4
class Handler
5
{
6
7
    /**
8
     * @var $argv
9
     */
10
    private $argv;
11
12
    /**
13
     * @var
14
     */
15
    private $command;
16
17
    /**
18
     *
19
     * @var array
20
     */
21
    private $commands = [];
22
23
    /**
24
     * @var array
25
     */
26
    private $input = [];
27
28
    /**
29
     * @var string
30
     */
31
    private $output;
32
33
    public function __construct($argv)
34
    {
35
        $this->argv = $argv;
36
    }
37
38
    public function addCommand(\Parking\Console\Command\Command $command)
39
    {
40
        $this->commands[] = $command;
41
    }
42
43
    public function dispatch()
44
    {
45
        $this->parseCommand();
46
        $this->parseInput();
47
        $this->executeCommand();
48
        $this->renderCommand();
49
50
        return $this->output;
51
    }
52
53
    public function executeCommand()
54
    {
55
        $this->output = $this->command->execute($this->input, $this->output);
56
    }
57
58
    public function parseCommand()
59
    {
60
        $className = isset($this->argv[1]) ? $this->argv[1] : get_class($this->commands[0]);
61
        $className = $this->parseClassName($className);
62
63
        $command = $this->getCommand($className);
64
        if (!$command) {
65
            throw new \Exception('Command not found');
66
        }
67
68
        $this->command = $command;
69
    }
70
71
    protected function parseClassName($name)
72
    {
73
        return "Parking\\Console\\Command\\" . implode('', array_map('ucwords', explode('_', $name)));
74
    }
75
76
    protected function parseInput()
77
    {
78
        $this->input = array_slice($this->argv, 2);
79
    }
80
81
    protected function getCommand($name)
82
    {
83
        foreach ($this->commands as $command) {
84
            if ($name === get_class($command)) {
85
                return $command;
86
            }
87
        }
88
89
        return false;
90
    }
91
92
    public function renderCommand()
93
    {
94
        fwrite(STDOUT, $this->output . PHP_EOL);
95
    }
96
}