| Conditions | 6 |
| Paths | 6 |
| Total Lines | 40 |
| Code Lines | 24 |
| Lines | 0 |
| Ratio | 0 % |
| Tests | 0 |
| CRAP Score | 42 |
| Changes | 0 | ||
| 1 | <?php |
||
| 10 | public function dispatch(string $job, array $params = [], string $service = null) |
||
|
|
|||
| 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 |
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: