Completed
Pull Request — master (#29)
by Aleh
03:01
created

Socket::loadCommands()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace Padawan\Framework\Application;
4
5
use Padawan\Framework\Application;
6
use Padawan\Framework\Application\Socket\SocketOutput;
7
use Symfony\Component\Console\Input\ArrayInput;
8
use Padawan\Command\CompleteCommand;
9
use Padawan\Command\KillCommand;
10
use Padawan\Command\ListCommand;
11
12
/**
13
 * Class Socket
14
 */
15
class Socket extends Application
16
{
17
    public function __construct()
18
    {
19
        parent::__construct("Padawan Server");
20
    }
21
22
    public function handle($request, SocketOutput $output)
23
    {
24
        if (!$request
25
            || !property_exists($request, "command")
26
            || !property_exists($request, "params")) {
27
            yield $output->write(json_encode([
28
                "error" => "Bad request"
29
            ]));
30
            return;
31
        }
32
        $arrayForInput = ['command' => $request->command];
33
        foreach($request->params as $key=>$value) {
34
            $arrayForInput[$key] =  $value;
35
        }
36
        $input = new ArrayInput($arrayForInput);
37
        $command = $this->find($request->command);
38
        try {
39
            yield from $command->run($input, $output);
40
        } catch (\Exception $e) {
41
            printf("Error: %s\n", $e->getMessage());
42
            yield $output->write(json_encode([
43
                "error" => $e->getMessage()
44
            ]));
45
        }
46
    }
47
48
    protected function loadCommands()
49
    {
50
        $this->add(new CompleteCommand);
51
        $this->add(new ListCommand);
52
        $this->add(new KillCommand);
53
    }
54
}
55