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

Socket::handle()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 25
Code Lines 18

Duplication

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