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

Dispatcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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