Passed
Push — master ( d93a6d...5a06fd )
by Dmitrij
03:06
created

Processor   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
dl 0
loc 64
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 13 2
A setArguments() 0 9 3
A getCommand() 0 9 2
A __construct() 0 5 1
A formatOutput() 0 6 1
1
<?php
2
3
namespace HotRodCli\Api;
4
5
use HotRodCli\AppContainer;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Symfony\Component\Console\Command\Command;
8
use \Symfony\Component\Console\Input\ArrayInput;
9
use Symfony\Component\Console\Output\BufferedOutput;
10
use Symfony\Component\Console\Application;
11
use Symfony\Component\Console\Output\OutputInterface;
12
13
class Processor
14
{
15
    protected $app;
16
17
    protected $commands;
18
19
    protected $data;
20
21
    protected $inputs;
22
23
    /** @var BufferedOutput */
24
    protected $output;
25
26
    public function __construct(AppContainer $appContainer)
27
    {
28
        $this->app = $appContainer;
29
        $this->commands = $this->app->resolve('commands');
30
        $this->output = $this->app->resolve(BufferedOutput::class);
31
    }
32
33
    public function __invoke(ServerRequestInterface $request, $args)
34
    {
35
        $this->data = $request->getParsedBody();
36
        /** @var Command $command */
37
        $command = $this->getCommand($args['command']);
38
        $this->setArguments();
39
        /** @var ArrayInput $arrayInput */
40
        $arrayInput = $this->app->resolve(ArrayInput::class, $this->inputs);
41
        $result = $command->run($arrayInput, $this->output);
42
43
        return json_encode([
44
            "success" => $result == 0 ? true : false,
45
            "output" => $this->formatOutput($this->output->fetch())
46
        ]);
47
    }
48
49
    public function getCommand($command)
50
    {
51
        if (isset($this->commands[$command])) {
52
            $application = $this->app->resolve(Application::class);
53
54
            return $application->find($command);
55
        }
56
57
        return null;
58
    }
59
60
    public function setArguments()
61
    {
62
        if ($this->data['arguments']) {
63
            foreach ($this->data['arguments'] as $key => $value) {
64
                $this->inputs[$key] = $value;
65
            }
66
        }
67
68
        return $this;
69
    }
70
71
    public function formatOutput(string $output)
72
    {
73
        $result = explode(PHP_EOL, $output);
74
        array_pop($result);
75
76
        return $result;
77
    }
78
}
79