Completed
Push — master ( f97a49...281390 )
by Dmitry
10:44
created

Dispatcher   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B dispatch() 0 35 6
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
    public function __construct(Client $etcd)
13
    {
14
        $this->etcd = $etcd;
15
    }
16
17
    public function dispatch($job, $params = [])
18
    {
19
        $this->etcd->setRoot('jobs');
20
21
        $service = $this->etcd->get($job);
22
        if(!$service) {
23
            throw new Exception("No service for job $job");
24
        }
25
26
        $host = getenv(strtoupper($service).'_SERVICE_HOST') ?: $service;
27
28
        $content = http_build_query([
29
            'rpc' => json_encode([
30
                'job' => $job,
31
                'params' => $params,
32
            ])
33
        ]);
34
35
        $context = stream_context_create([
36
            'http' => [
37
                'method' => 'POST',
38
                'header' => 'Content-Type: application/x-www-form-urlencoded',
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