Completed
Pull Request — master (#146)
by Alexander
06:11
created

AbstractServiceClient::getServiceDomain()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Yandex PHP Library
4
 *
5
 * @copyright NIX Solutions Ltd.
6
 * @link https://github.com/nixsolutions/yandex-php-library
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Yandex\Common;
13
14
use GuzzleHttp\Client;
15
use GuzzleHttp\ClientInterface;
16
use Psr\Http\Message\UriInterface;
17
use GuzzleHttp\Exception\ClientException;
18
use GuzzleHttp\Psr7\Response;
19
use Yandex\Common\Exception\MissedArgumentException;
20
use Yandex\Common\Exception\ProfileNotFoundException;
21
use Yandex\Common\Exception\YandexException;
22
23
/**
24
 * Class AbstractServiceClient
25
 *
26
 * @package Yandex\Common
27
 *
28
 * @author   Eugene Zabolotniy <[email protected]>
29
 * @created  13.09.13 12:09
30
 */
31
abstract class AbstractServiceClient extends AbstractPackage
32
{
33
    /**
34
     * Request schemes constants
35
     */
36
    const HTTPS_SCHEME = 'https';
37
    const HTTP_SCHEME = 'http';
38
39
    const DECODE_TYPE_JSON = 'json';
40
    const DECODE_TYPE_XML = 'xml';
41
    const DECODE_TYPE_DEFAULT = self::DECODE_TYPE_JSON;
42
43
    /**
44
     * @var string
45
     */
46
    protected $serviceScheme = self::HTTPS_SCHEME;
47
48
    /**
49
     * Can be HTTP 1.0 or HTTP 1.1
50
     * @var string
51
     */
52
    protected $serviceProtocolVersion = '1.1';
53
54
    /**
55
     * @var string
56
     */
57
    protected $serviceDomain = '';
58
59
    /**
60
     * @var string
61
     */
62
    protected $servicePort = '';
63
64
    /**
65
     * @var string
66
     */
67
    protected $accessToken = '';
68
69
    /**
70
     * @var string
71
     */
72
    protected $proxy = '';
73
74
    /**
75
     * @var bool
76
     */
77
    protected $debug = false;
78
79
    /**
80
     * @var null
81
     */
82
    protected $client = null;
83
84
    /**
85
     * @var string
86
     */
87
    protected $libraryName = 'yandex-php-library';
88
89
    /**
90
     * @return string
91
     */
92 12
    public function getUserAgent()
93
    {
94 12
        return $this->libraryName . '/' . Version::$version;
95
    }
96
97
    /**
98
     * @param string $accessToken
99
     *
100
     * @return self
101
     */
102 85
    public function setAccessToken($accessToken)
103
    {
104 85
        $this->accessToken = $accessToken;
105
106 85
        return $this;
107
    }
108
109
    /**
110
     * @return string
111
     */
112 15
    public function getAccessToken()
113
    {
114 15
        return $this->accessToken;
115
    }
116
117
    /**
118
     * @param $proxy
119
     * @return $this
120
     */
121
    public function setProxy($proxy)
122
    {
123
        $this->proxy = $proxy;
124
125
        return $this;
126
    }
127
128
    /**
129
     * @return string
130
     */
131 12
    public function getProxy()
132
    {
133 12
        return $this->proxy;
134
    }
135
136
    /**
137
     * @param $debug
138
     * @return $this
139
     */
140
    public function setDebug($debug)
141
    {
142
        $this->debug = (bool) $debug;
143
144
        return $this;
145
    }
146
147
    /**
148
     * @return bool
149
     */
150 12
    public function getDebug()
151
    {
152 12
        return $this->debug;
153
    }
154
155
    /**
156
     * @param string $serviceDomain
157
     *
158
     * @return self
159
     */
160 4
    public function setServiceDomain($serviceDomain)
161
    {
162 4
        $this->serviceDomain = $serviceDomain;
163
164 4
        return $this;
165
    }
166
167
    /**
168
     * @return string
169
     */
170 18
    public function getServiceDomain()
171
    {
172 18
        return $this->serviceDomain;
173
    }
174
175
    /**
176
     * @param string $servicePort
177
     *
178
     * @return self
179
     */
180 4
    public function setServicePort($servicePort)
181
    {
182 4
        $this->servicePort = $servicePort;
183
184 4
        return $this;
185
    }
186
187
    /**
188
     * @return string
189
     */
190 4
    public function getServicePort()
191
    {
192 4
        return $this->servicePort;
193
    }
194
195
    /**
196
     * @param string $serviceScheme
197
     *
198
     * @return self
199
     */
200 4
    public function setServiceScheme($serviceScheme = self::HTTPS_SCHEME)
201
    {
202 4
        $this->serviceScheme = $serviceScheme;
203
204 4
        return $this;
205
    }
206
207
    /**
208
     * @return string
209
     */
210 6
    public function getServiceScheme()
211
    {
212 6
        return $this->serviceScheme;
213
    }
214
215
    /**
216
     * @param string $resource
217
     * @return string
218
     */
219 16
    public function getServiceUrl($resource = '')
220
    {
221 16
        return $this->serviceScheme . '://' . $this->serviceDomain . '/' . rawurlencode($resource);
222
    }
223
224
    /**
225
     * Check package configuration
226
     *
227
     * @return boolean
228
     */
229
    protected function doCheckSettings()
230
    {
231
        return true;
232
    }
233
234
    /**
235
     * @param ClientInterface $client
236
     * @return $this
237
     */
238 1
    protected function setClient(ClientInterface $client)
239
    {
240 1
        $this->client = $client;
0 ignored issues
show
Documentation Bug introduced by
It seems like $client of type object<GuzzleHttp\ClientInterface> is incompatible with the declared type null of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
241
242 1
        return $this;
243
    }
244
245
    /**
246
     * @return ClientInterface
247
     */
248 13 View Code Duplication
    protected function getClient()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
249
    {
250 13
        if (is_null($this->client)) {
251
            $defaultOptions = [
252 12
                'base_uri' => $this->getServiceUrl(),
253
                'headers' => [
254 12
                    'Authorization' => 'OAuth ' . $this->getAccessToken(),
255 12
                    'Host' => $this->getServiceDomain(),
256 12
                    'User-Agent' => $this->getUserAgent(),
257
                    'Accept' => '*/*'
258 12
                ]
259 12
            ];
260 12
            if ($this->getProxy()) {
261
                $defaultOptions['proxy'] = $this->getProxy();
262
            }
263 12
            if ($this->getDebug()) {
264
                $defaultOptions['debug'] = $this->getDebug();
265
            }
266 12
            $this->client = new Client($defaultOptions);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \GuzzleHttp\Client($defaultOptions) of type object<GuzzleHttp\Client> is incompatible with the declared type null of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
267 12
        }
268
269 13
        return $this->client;
270
    }
271
272
    /**
273
     * Sends a request
274
     *
275
     * @param string              $method  HTTP method
276
     * @param string|UriInterface $uri     URI object or string.
277
     * @param array               $options Request options to apply.
278
     *
279
     * @throws Exception\MissedArgumentException
280
     * @throws Exception\ProfileNotFoundException
281
     * @throws Exception\YandexException
282
     * @return Response
283
     */
284 8
    protected function sendRequest($method, $uri, array $options = [])
285
    {
286
        try {
287 8
            $response = $this->getClient()->request($method, $uri, $options);
288 8
        } catch (ClientException $ex) {
289
            // get error from response
290
            $decodedResponseBody = $this->getDecodedBody($ex->getResponse()->getBody());
291
            $code = $ex->getResponse()->getStatusCode();
292
293
            // handle a service error message
294
            if (is_array($decodedResponseBody)
295
                && isset($decodedResponseBody['error'], $decodedResponseBody['message'])
296
            ) {
297
                switch ($decodedResponseBody['error']) {
298
                    case 'MissedRequiredArguments':
299
                        throw new MissedArgumentException($decodedResponseBody['message']);
300
                    case 'AssistantProfileNotFound':
301
                        throw new ProfileNotFoundException($decodedResponseBody['message']);
302
                    default:
303
                        throw new YandexException($decodedResponseBody['message'], $code);
304
                }
305
            }
306
307
            // unknown error
308
            throw $ex;
309
        }
310
311 8
        return $response;
312
    }
313
314
    /**
315
     * @param $body
316
     * @param string $type
317
     * @return mixed|\SimpleXMLElement
318
     */
319 56
    protected function getDecodedBody($body, $type = null)
320
    {
321 56
        if (!isset($type)) {
322 56
            $type = static::DECODE_TYPE_DEFAULT;
323 56
        }
324
        switch ($type) {
325 56
            case self::DECODE_TYPE_XML:
326 6
                return simplexml_load_string((string) $body);
327 50
            case self::DECODE_TYPE_JSON:
328 50
            default:
329 50
                return json_decode((string) $body, true);
330
        }
331
    }
332
}
333