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

Socket   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6
Metric Value
wmc 8
lcom 0
cbo 6
dl 0
loc 39
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B handle() 0 25 6
A loadCommands() 0 5 1
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