Conditions | 6 |
Paths | 6 |
Total Lines | 40 |
Code Lines | 24 |
Lines | 0 |
Ratio | 0 % |
Tests | 0 |
CRAP Score | 42 |
Changes | 0 |
1 | <?php |
||
17 | public function dispatch(string $job, array $params = [], string $service = null) |
||
|
|||
18 | { |
||
19 | if (!$service) { |
||
20 | $service = 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 | 'content' => $content, |
||
35 | 'header' => implode([ |
||
36 | 'content-type: application/x-www-form-urlencoded', |
||
37 | 'x-real-ip: '.$_SERVER['HTTP_X_REAL_IP'], |
||
38 | 'x-session: '.$_SERVER['HTTP_X_SESSION'], |
||
39 | ], "\r\n"), |
||
40 | 'ignore_errors' => '1' |
||
41 | ], |
||
42 | ]); |
||
43 | |||
44 | $contents = file_get_contents("http://$service/api", false, $context); |
||
45 | |||
46 | if (!$contents) { |
||
47 | throw new Exception("Host $service unreachable"); |
||
48 | } |
||
49 | |||
50 | $result = json_decode($contents); |
||
51 | if (!$result || !$result->success) { |
||
52 | throw new Exception($result->message ?: $contents); |
||
53 | } |
||
54 | |||
55 | return $result->data; |
||
56 | } |
||
57 | } |
||
58 |
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: