Conditions | 7 |
Paths | 7 |
Total Lines | 44 |
Code Lines | 25 |
Lines | 0 |
Ratio | 0 % |
Tests | 0 |
CRAP Score | 56 |
Changes | 0 |
1 | <?php |
||
17 | public function dispatch($job, $params = [], $host = null) |
||
|
|||
18 | { |
||
19 | |||
20 | if(!$host) { |
||
21 | |||
22 | $this->etcd->setRoot('jobs'); |
||
23 | |||
24 | $service = $this->etcd->get($job); |
||
25 | if(!$service) { |
||
26 | throw new Exception("No service for job $job"); |
||
27 | } |
||
28 | |||
29 | $host = getenv(strtoupper($service).'_SERVICE_HOST') ?: $service; |
||
30 | } |
||
31 | |||
32 | $content = http_build_query([ |
||
33 | 'rpc' => json_encode([ |
||
34 | 'job' => $job, |
||
35 | 'params' => $params, |
||
36 | ]) |
||
37 | ]); |
||
38 | |||
39 | |||
40 | $context = stream_context_create([ |
||
41 | 'http' => [ |
||
42 | 'method' => 'POST', |
||
43 | 'header' => implode([ |
||
44 | 'content-type: application/x-www-form-urlencoded', |
||
45 | 'x-real-ip: '.$_SERVER['HTTP_X_REAL_IP'], |
||
46 | 'x-session: '.$_SERVER['HTTP_X_SESSION'], |
||
47 | ], "\r\n"), |
||
48 | 'content' => $content, |
||
49 | ], |
||
50 | ]); |
||
51 | |||
52 | $contents = file_get_contents("http://$host/api", false, $context); |
||
53 | |||
54 | $result = json_decode($contents); |
||
55 | if(!$result || !$result->success) { |
||
56 | throw new Exception($result->message ?: $contents); |
||
57 | } |
||
58 | |||
59 | return $result->data; |
||
60 | } |
||
61 | } |
||
62 |
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: