Socket::handle()   C
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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