Completed
Push — master ( 735ffd...9b092c )
by Anton
8s
created

MetricaClient::sendRequest()   D

Complexity

Conditions 9
Paths 16

Size

Total Lines 41
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 9

Importance

Changes 7
Bugs 2 Features 3
Metric Value
c 7
b 2
f 3
dl 0
loc 41
ccs 25
cts 25
cp 1
rs 4.909
cc 9
eloc 24
nc 16
nop 3
crap 9
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\Metrica;
13
14
use GuzzleHttp\ClientInterface;
15
use Yandex\Common\AbstractServiceClient;
16
use Psr\Http\Message\UriInterface;
17
use GuzzleHttp\Psr7\Response;
18
use GuzzleHttp\Exception\ClientException;
19
use Yandex\Common\Exception\ForbiddenException;
20
use Yandex\Common\Exception\UnauthorizedException;
21
use Yandex\Common\Exception\TooManyRequestsException;
22
use Yandex\Metrica\Exception\BadRequestException;
23
use Yandex\Metrica\Exception\MetricaException;
24
25
/**
26
 * Class MetricaClient
27
 *
28
 * @category Yandex
29
 * @package Metrica
30
 *
31
 * @author   Alexander Khaylo <[email protected]>
32
 * @created  12.02.14 15:46
33
 */
34
class MetricaClient extends AbstractServiceClient
35
{
36
    /**
37
     * API domain
38
     *
39
     * @var string
40
     */
41
    protected $serviceDomain = 'api-metrika.yandex.ru/management/v1';
42
43
    /**
44
     * @param string $token access token
45
     * @param ClientInterface $client
46
     */
47 58
    public function __construct($token = '', ClientInterface $client = null)
48
    {
49 58
        $this->setAccessToken($token);
50 58
        if (!is_null($client)) {
51 1
            $this->setClient($client);
52 1
        }
53 58
    }
54
55
    /**
56
     * Get url to service resource with parameters
57
     *
58
     * @param string $resource
59
     * @param array $params
60
     * @see http://api.yandex.ru/metrika/doc/ref/concepts/method-call.xml
61
     * @return string
62
     */
63 29
    public function getServiceUrl($resource = '', $params = [])
64
    {
65 29
        $format = $resource === '' ? '' : '.json';
66 29
        $url = $this->serviceScheme . '://' . $this->serviceDomain . '/'
67 29
            . $resource . $format . '?oauth_token=' . $this->getAccessToken();
68
69 29
        if ($params) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $params of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
70 2
            $url .= '&' . http_build_query($params);
71 2
        }
72
73 29
        return $url;
74
    }
75
76
    /**
77
     * Sends a request
78
     *
79
     * @param string              $method  HTTP method
80
     * @param string|UriInterface $uri     URI object or string.
81
     * @param array               $options Request options to apply.
82
     *
83
     * @return Response
84
     *
85
     * @throws BadRequestException
86
     * @throws ForbiddenException
87
     * @throws MetricaException
88
     * @throws TooManyRequestsException
89
     * @throws UnauthorizedException
90
     */
91 27
    protected function sendRequest($method, $uri, array $options = [])
92
    {
93
        try {
94 27
            $response = $this->getClient()->request($method, $uri, $options);
0 ignored issues
show
Bug introduced by
It seems like $uri defined by parameter $uri on line 91 can also be of type object<Psr\Http\Message\UriInterface>; however, GuzzleHttp\Client::request() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
95 27
        } catch (ClientException $ex) {
96 5
            $result = $ex->getResponse();
97 5
            $code = $result->getStatusCode();
98 5
            $message = $result->getReasonPhrase();
99
100 5
            $body = $result->getBody();
101 5
            if ($body) {
102 5
                $jsonBody = json_decode($body);
103 5
                if ($jsonBody && isset($jsonBody->message)) {
104 1
                    $message = $jsonBody->message;
105 1
                }
106 5
            }
107
108 5
            if ($code === 400) {
109 1
                throw new BadRequestException($message);
110
            }
111
112 4
            if ($code === 403) {
113 1
                throw new ForbiddenException($message);
114
            }
115
116 3
            if ($code === 401) {
117 1
                throw new UnauthorizedException($message);
118
            }
119
120 2
            if ($code === 429) {
121 1
                throw new TooManyRequestsException($message);
122
            }
123
124 1
            throw new MetricaException(
125 1
                'Service responded with error code: "' . $code . '" and message: "' . $message . '"',
126
                $code
127 1
            );
128
        }
129
130 22
        return $response;
131
    }
132
133
    /**
134
     * Send GET request to API resource
135
     *
136
     * @param string $resource
137
     * @param array $params
138
     * @return array
139
     */
140 6
    protected function sendGetRequest($resource, $params = [])
141
    {
142 6
        $response = $this->sendRequest(
143 6
            'GET',
144 6
            $this->getServiceUrl($resource, $params),
145
            [
146
                'headers' => [
147 6
                    'Accept' => 'application/x-yametrika+json',
148 6
                    'Content-Type' => 'application/x-yametrika+json',
149
                ]
150 6
            ]
151 6
        );
152
153 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
154
155 1 View Code Duplication
        if (isset($decodedResponseBody['links']) && isset($decodedResponseBody['links']['next'])) {
0 ignored issues
show
Duplication introduced by
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...
156
            $url = $decodedResponseBody['links']['next'];
157
            unset($decodedResponseBody['rows']);
158
            unset($decodedResponseBody['links']);
159
            return $this->getNextPartOfList($url, $decodedResponseBody);
160
        }
161 1
        return $decodedResponseBody;
162
    }
163
164
    /**
165
     * Send custom GET request to API resource
166
     *
167
     * @param string $url
168
     * @param array $data
169
     * @return array
170
     */
171
    protected function getNextPartOfList($url, $data = [])
172
    {
173
        $response = $this->sendRequest(
174
            'GET',
175
            $url,
176
            [
177
                'headers' => [
178
                    'Accept' => 'application/x-yametrika+json',
179
                    'Content-Type' => 'application/x-yametrika+json',
180
                ]
181
            ]
182
        );
183
184
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
185
186
        $mergedDecodedResponseBody = array_merge_recursive($data, $decodedResponseBody);
187
188 View Code Duplication
        if (isset($mergedDecodedResponseBody['links']) && isset($mergedDecodedResponseBody['links']['next'])) {
0 ignored issues
show
Duplication introduced by
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...
189
            $url = $mergedDecodedResponseBody['links'];
190
            unset($mergedDecodedResponseBody['rows']);
191
            unset($mergedDecodedResponseBody['links']);
192
            return $this->getNextPartOfList($url, $response);
0 ignored issues
show
Documentation introduced by
$response is of type object<GuzzleHttp\Psr7\Response>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
193
        }
194
195
        return $mergedDecodedResponseBody;
196
    }
197
198
    /**
199
     * Send POST request to API resource
200
     *
201
     * @param string $resource
202
     * @param array $params
203
     * @return array
204
     */
205 7 View Code Duplication
    protected function sendPostRequest($resource, $params)
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...
206
    {
207 7
        $response = $this->sendRequest(
208 7
            'POST',
209 7
            $this->getServiceUrl($resource),
210
            [
211
                'headers' => [
212 7
                    'Accept' => 'application/x-yametrika+json',
213 7
                    'Content-Type' => 'application/x-yametrika+json',
214 7
                ],
215
                'json' => $params
216 7
            ]
217 7
        );
218
219 7
        return $this->getDecodedBody($response->getBody());
220
    }
221
222
    /**
223
     * Send PUT request to API resource
224
     *
225
     * @param string $resource
226
     * @param array $params
227
     * @return array
228
     */
229 7 View Code Duplication
    protected function sendPutRequest($resource, $params)
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...
230
    {
231 7
        $response = $this->sendRequest(
232 7
            'PUT',
233 7
            $this->getServiceUrl($resource),
234
            [
235
                'headers' => [
236 7
                    'Accept' => 'application/x-yametrika+json',
237 7
                    'Content-Type' => 'application/x-yametrika+json',
238 7
                ],
239
                'json' => $params
240 7
            ]
241 7
        );
242
243 7
        return $this->getDecodedBody($response->getBody());
244
    }
245
246
    /**
247
     * Send DELETE request to API resource
248
     *
249
     * @param string $resource
250
     * @return array
251
     */
252 7 View Code Duplication
    protected function sendDeleteRequest($resource)
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...
253
    {
254 7
        $response = $this->sendRequest(
255 7
            'DELETE',
256 7
            $this->getServiceUrl($resource),
257
            [
258
                'headers' => [
259 7
                    'Accept' => 'application/x-yametrika+json',
260 7
                    'Content-Type' => 'application/x-yametrika+json',
261
                ]
262 7
            ]
263 7
        );
264
265 7
        return $this->getDecodedBody($response->getBody());
266
    }
267
}
268