Completed
Push — master ( a739b1...819589 )
by Anton
07:22 queued 05:17
created

MetricaClient::sendGetRequest()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 23
Code Lines 14

Duplication

Lines 6
Ratio 26.09 %

Code Coverage

Tests 8
CRAP Score 3.3332

Importance

Changes 0
Metric Value
dl 6
loc 23
ccs 8
cts 12
cp 0.6667
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 14
nc 2
nop 2
crap 3.3332
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 GuzzleHttp\Psr7\Response;
17
use GuzzleHttp\Exception\ClientException;
18
use Yandex\Common\Exception\ForbiddenException;
19
use Yandex\Common\Exception\UnauthorizedException;
20
use Yandex\Common\Exception\TooManyRequestsException;
21
use Yandex\Metrica\Exception\BadRequestException;
22
use Yandex\Metrica\Exception\MetricaException;
23
24
/**
25
 * Class MetricaClient
26
 *
27
 * @category Yandex
28
 * @package Metrica
29
 *
30
 * @author   Alexander Khaylo <[email protected]>
31
 * @created  12.02.14 15:46
32
 */
33
class MetricaClient extends AbstractServiceClient
34
{
35
    /**
36
     * API domain
37
     *
38
     * @var string
39
     */
40
    protected $serviceDomain = 'api-metrika.yandex.ru/management/v1';
41
42
    /**
43
     * @param string $token access token
44
     * @param ClientInterface $client
45
     */
46 58
    public function __construct($token = '', ClientInterface $client = null)
47
    {
48 58
        $this->setAccessToken($token);
49 58
        if (!is_null($client)) {
50 1
            $this->setClient($client);
51
        }
52 58
    }
53
54
    /**
55
     * Get url to service resource with parameters
56
     *
57
     * @param string $resource
58
     * @param array $params
59
     * @see http://api.yandex.ru/metrika/doc/ref/concepts/method-call.xml
60
     * @return string
61
     */
62 29
    public function getServiceUrl($resource = '', $params = [])
63
    {
64 29
        $format = $resource === '' ? '' : '.json';
65 29
        $url = $this->serviceScheme . '://' . $this->serviceDomain . '/'
66 29
            . $resource . $format . '?oauth_token=' . $this->getAccessToken();
67
68 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...
69 2
            $url .= '&' . http_build_query($params);
70
        }
71
72 29
        return $url;
73
    }
74
75
    /**
76
     * Sends a request
77
     *
78
     * @param string              $method  HTTP method
79
     * @param string $uri     URI object or string.
80
     * @param array               $options Request options to apply.
81
     *
82
     * @return Response
83
     *
84
     * @throws BadRequestException
85
     * @throws ForbiddenException
86
     * @throws MetricaException
87
     * @throws TooManyRequestsException
88
     * @throws UnauthorizedException
89
     */
90 27
    protected function sendRequest($method, $uri, array $options = [])
91
    {
92
        try {
93 27
            $response = $this->getClient()->request($method, $uri, $options);
94 5
        } catch (ClientException $ex) {
95 5
            $result = $ex->getResponse();
96 5
            $code = $result->getStatusCode();
97 5
            $message = $result->getReasonPhrase();
98
99 5
            $body = $result->getBody();
100 5
            if ($body) {
101 5
                $jsonBody = json_decode($body);
102 5
                if ($jsonBody && isset($jsonBody->message)) {
103 1
                    $message = $jsonBody->message;
104
                }
105
            }
106
107 5
            if ($code === 400) {
108 1
                throw new BadRequestException($message);
109
            }
110
111 4
            if ($code === 403) {
112 1
                throw new ForbiddenException($message);
113
            }
114
115 3
            if ($code === 401) {
116 1
                throw new UnauthorizedException($message);
117
            }
118
119 2
            if ($code === 429) {
120 1
                throw new TooManyRequestsException($message);
121
            }
122
123 1
            throw new MetricaException(
124 1
                'Service responded with error code: "' . $code . '" and message: "' . $message . '"',
125 1
                $code
126
            );
127
        }
128
129 22
        return $response;
130
    }
131
132
    /**
133
     * Send GET request to API resource
134
     *
135
     * @param string $resource
136
     * @param array $params
137
     * @return array
138
     */
139 6
    protected function sendGetRequest($resource, $params = [])
140
    {
141 6
        $response = $this->sendRequest(
142 6
            'GET',
143 6
            $this->getServiceUrl($resource, $params),
144
            [
145 6
                'headers' => [
146
                    'Accept' => 'application/x-yametrika+json',
147
                    'Content-Type' => 'application/x-yametrika+json',
148
                ]
149
            ]
150
        );
151
152 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
153
154 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...
155
            $url = $decodedResponseBody['links']['next'];
156
            unset($decodedResponseBody['rows']);
157
            unset($decodedResponseBody['links']);
158
            return $this->getNextPartOfList($url, $decodedResponseBody);
159
        }
160 1
        return $decodedResponseBody;
161
    }
162
163
    /**
164
     * Send custom GET request to API resource
165
     *
166
     * @param string $url
167
     * @param array $data
168
     * @return array
169
     */
170
    protected function getNextPartOfList($url, $data = [])
171
    {
172
        $response = $this->sendRequest(
173
            'GET',
174
            $url,
175
            [
176
                'headers' => [
177
                    'Accept' => 'application/x-yametrika+json',
178
                    'Content-Type' => 'application/x-yametrika+json',
179
                ]
180
            ]
181
        );
182
183
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
184
185
        $mergedDecodedResponseBody = array_merge_recursive($data, $decodedResponseBody);
186
187 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...
188
            $url = $mergedDecodedResponseBody['links'];
189
            unset($mergedDecodedResponseBody['rows']);
190
            unset($mergedDecodedResponseBody['links']);
191
            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...
192
        }
193
194
        return $mergedDecodedResponseBody;
195
    }
196
197
    /**
198
     * Send POST request to API resource
199
     *
200
     * @param string $resource
201
     * @param array $params
202
     * @return array
203
     */
204 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...
205
    {
206 7
        $response = $this->sendRequest(
207 7
            'POST',
208 7
            $this->getServiceUrl($resource),
209
            [
210 7
                'headers' => [
211
                    'Accept' => 'application/x-yametrika+json',
212
                    'Content-Type' => 'application/x-yametrika+json',
213
                ],
214 7
                'json' => $params
215
            ]
216
        );
217
218 7
        return $this->getDecodedBody($response->getBody());
219
    }
220
221
    /**
222
     * Send PUT request to API resource
223
     *
224
     * @param string $resource
225
     * @param array $params
226
     * @return array
227
     */
228 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...
229
    {
230 7
        $response = $this->sendRequest(
231 7
            'PUT',
232 7
            $this->getServiceUrl($resource),
233
            [
234 7
                'headers' => [
235
                    'Accept' => 'application/x-yametrika+json',
236
                    'Content-Type' => 'application/x-yametrika+json',
237
                ],
238 7
                'json' => $params
239
            ]
240
        );
241
242 7
        return $this->getDecodedBody($response->getBody());
243
    }
244
245
    /**
246
     * Send DELETE request to API resource
247
     *
248
     * @param string $resource
249
     * @return array
250
     */
251 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...
252
    {
253 7
        $response = $this->sendRequest(
254 7
            'DELETE',
255 7
            $this->getServiceUrl($resource),
256
            [
257 7
                'headers' => [
258
                    'Accept' => 'application/x-yametrika+json',
259
                    'Content-Type' => 'application/x-yametrika+json',
260
                ]
261
            ]
262
        );
263
264 7
        return $this->getDecodedBody($response->getBody());
265
    }
266
}
267