Completed
Push — master ( 4967cd...fefc41 )
by Dmitry
16:49
created

Dispatcher::getServiceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Basis;
4
5
use Basis\Context;
6
use Exception;
7
use GuzzleHttp\Client;
8
9
class Dispatcher
10
{
11
    protected $client;
12
    protected $context;
13
    protected $service;
14
15 1
    public function __construct(Client $client, Context $context, Service $service)
16
    {
17 1
        $this->client = $client;
18 1
        $this->context = $context;
19 1
        $this->service = $service;
20 1
    }
21
22 1
    public function dispatch(string $job, array $params = [], string $service = null, $context = null)
23
    {
24 1
        return $this->dispatchAsync($job, $params, $service, $context)->wait();
25
    }
26
27 1
    public function dispatchAsync(string $job, array $params = [], string $service = null, $context = null)
28
    {
29 1
        if ($service === null) {
30 1
            $service = $this->getServiceName($job);
31
        }
32
33 1
        $url = $this->getUrl($service, $job);
34 1 View Code Duplication
        if (is_array($params) && array_key_exists('eventId', $params)) {
0 ignored issues
show
Duplication introduced by Dmitry Krokhin
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
35
            $url .= '/'.$params['eventId'];
36
        }
37
38 1
        if (!$context) {
39 1
            $context = $this->getContext();
40
        }
41
42 1
        $response = $this->client->postAsync($url, [
43
            'multipart' => [
44
                [
45 1
                    'name' => 'rpc',
46 1
                    'contents' => json_encode([
47 1
                        'context' => $context,
48 1
                        'job'     => $job,
49 1
                        'params'  => $params,
50
                    ])
51
                ]
52
            ]
53
        ]);
54
55 1
        return $response->then(function ($response) {
56 1
            $contents = $response->getBody();
57 1
            if (!$contents) {
58
                throw new Exception("Host $host ($service) is unreachable");
59
            }
60
    
61 1
            $result = json_decode($contents);
62 1
            if (!$result || !$result->success) {
63
                $exception = new Exception($result->message ?: $contents);
64
                if ($result->trace) {
65
                    $exception->remoteTrace = $result->trace;
0 ignored issues
show
Bug introduced by Dmitry Krokhin
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...
66
                }
67
                throw $exception;
68
            }
69
    
70 1
            return $result->data;
71 1
        });
72
    }
73
74 1
    protected function getContext() : array
75
    {
76 1
        $context = get_object_vars($this->context);
77
    
78 1
        if (array_key_exists('HTTP_X_REAL_IP', $_SERVER)) {
79
            $context['host'] = $_SERVER['HTTP_X_REAL_IP'];
80
        }
81
82 1
        if (array_key_exists('HTTP_X_SESSION', $_SERVER)) {
83
            $context['session'] = $_SERVER['HTTP_X_SESSION'];
84
        }
85
86 1
        return $context;
87
    }
88
89 1
    protected function getServiceName(string $job) : string
90
    {
91 1
        return explode('.', $job)[0];
92
    }
93
94 1
    protected function getUrl(string $service, string $job) : string
95
    {
96 1
        $host = $this->service->getHost($service)->address;
97 1
        return "http://$host/api/" . str_replace('.', '/', $job);
98
    }
99
100
    public function send(string $job, array $params = [], string $service = null, $context = null) : boolean
101
    {
102
        if ($service === null) {
103
            $service = $this->getServiceName($job);
104
        }
105
106
        $url = $this->getUrl($service, $job);
107 View Code Duplication
        if (is_array($params) && array_key_exists('eventId', $params)) {
0 ignored issues
show
Duplication introduced by Dmitry Krokhin
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
            $url .= '/'.$params['eventId'];
109
        }
110
111
        if (!$context) {
112
            $context = $this->getContext();
113
        }
114
115
        $rpc = [
116
            'context' => $context,
117
            'job'     => $job,
118
            'params'  => $params,
119
        ];
120
121
        $content = 'rpc='.urlencode(json_encode($rpc));
122
123
        $parts = parse_url($url);
124
        $port = isset($parts['port']) ? $parts['port'] : 80;
125
        $fp = fsockopen($parts['host'], $port, $errno, $errstr, 30);
126
127
        if (!$fp) {
128
            return false;
129
        }
130
131
        fwrite($fp, implode("\r\n", [
132
            "POST " . $parts['path'] . " HTTP/1.1",
133
            "Host: " . $parts['host'],
134
            "Content-Type: application/x-www-form-urlencoded",
135
            "Content-Length: " . strlen($content),
136
            "Connection: Close",
137
            "",
138
            isset($content) ? $content : '',
139
        ]));
140
141
        fclose($fp);
142
143
        return true;
144
    }
145
}
146