Completed
Push — master ( ec95d0...1ede21 )
by Dmitry
03:27
created

Dispatcher::dispatch()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 0
cts 20
cp 0
rs 8.439
c 0
b 0
f 0
cc 5
eloc 21
nc 4
nop 3
crap 30
1
<?php
2
3
namespace Basis;
4
5
use Exception;
6
use LinkORB\Component\Etcd\Client;
7
8
class Dispatcher
9
{
10
    private $etcd;
11
12 1
    public function __construct(Client $etcd)
13
    {
14 1
        $this->etcd = $etcd;
15 1
    }
16
17
    public function dispatch($job, $params = [], $host = null)
0 ignored issues
show
Coding Style introduced by
dispatch uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
18
    {
19
        if (!$host) {
20
            $host = explode('.', $job)[0];
21
        }
22
23
        $content = http_build_query([
24
            'rpc' => json_encode([
25
                'job' => $job,
26
                'params' => $params,
27
            ])
28
        ]);
29
30
31
        $context = stream_context_create([
32
            'http' => [
33
                'method' => 'POST',
34
                'header' => implode([
35
                    'content-type: application/x-www-form-urlencoded',
36
                    'x-real-ip: '.$_SERVER['HTTP_X_REAL_IP'],
37
                    'x-session: '.$_SERVER['HTTP_X_SESSION'],
38
                ], "\r\n"),
39
                'content' => $content,
40
            ],
41
        ]);
42
43
        $contents = file_get_contents("http://$host/api", false, $context);
44
45
        $result = json_decode($contents);
46
        if (!$result || !$result->success) {
47
            throw new Exception($result->message ?: $contents);
48
        }
49
50
        return $result->data;
51
    }
52
}
53