Completed
Push — master ( e65a89...680409 )
by Dmitry
04:53
created

Dispatcher   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 79.17%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 50
ccs 19
cts 24
cp 0.7917
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B dispatch() 0 38 7
1
<?php
2
3
namespace Basis;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
8
class Dispatcher
9
{
10
    protected $client;
11
    protected $service;
12
13 1
    public function __construct(Client $client, Service $service)
14
    {
15 1
        $this->client = $client;
16 1
        $this->service = $service;
17 1
    }
18
19 1
    public function dispatch(string $job, array $params = [], string $service = null)
20
    {
21 1
        if ($service === null) {
22 1
            $service = explode('.', $job)[0];
23
        }
24
25 1
        $host = $this->service->getHost($service)->address;
26 1
        $url = "http://$host/api/" . str_replace('.', '/', $job);
27
28 1
        $response = $this->client->post($url, [
29
            'multipart' => [
30
                [
31 1
                    'name' => 'rpc',
32 1
                    'contents' => json_encode([
33 1
                        'job'    => $job,
34 1
                        'params' => $params,
35
                    ])
36
                ]
37
            ]
38
        ]);
39
40 1
        $contents = $response->getBody();
41
42 1
        if (!$contents) {
43
            throw new Exception("Host $host ($service) is unreachable");
44
        }
45
46 1
        $result = json_decode($contents);
47 1
        if (!$result || !$result->success) {
48
            $exception = new Exception($result->message ?: $contents);
49
            if ($result->trace) {
50
                $exception->remoteTrace = $result->trace;
0 ignored issues
show
Bug introduced by
The property remoteTrace does not seem to exist in Exception.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
51
            }
52
            throw $exception;
53
        }
54
55 1
        return $result->data;
56
    }
57
}
58