Completed
Push — master ( 9d8998...346ad6 )
by Dmitry
03:39
created

Dispatcher   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 43
ccs 0
cts 23
cp 0
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B dispatch() 0 40 6
1
<?php
2
3
namespace Basis;
4
5
use Exception;
6
use LinkORB\Component\Etcd\Client;
7
8
class Dispatcher
9
{
10
    public function dispatch(string $job, array $params = [], string $service = 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...
11
    {
12
        if ($service === null) {
13
            $service = explode('.', $job)[0];
14
        }
15
16
        $content = http_build_query([
17
            'rpc' => json_encode([
18
                'job'    => $job,
19
                'params' => $params,
20
            ])
21
        ]);
22
23
24
        $context = stream_context_create([
25
            'http' => [
26
                'method'  => 'POST',
27
                'content' => $content,
28
                'header'  => implode([
29
                    'content-type: application/x-www-form-urlencoded',
30
                    'x-real-ip: '.$_SERVER['HTTP_X_REAL_IP'],
31
                    'x-session: '.$_SERVER['HTTP_X_SESSION'],
32
                ], "\r\n"),
33
                'ignore_errors' => '1'
34
            ],
35
        ]);
36
37
        $contents = file_get_contents("http://$service/api", false, $context);
38
39
        if (!$contents) {
40
            throw new Exception("Host $service unreachable");
41
        }
42
43
        $result = json_decode($contents);
44
        if (!$result || !$result->success) {
45
            throw new Exception($result->message ?: $contents);
46
        }
47
48
        return $result->data;
49
    }
50
}
51