Completed
Pull Request — master (#155)
by Alexander
06:33
created

MetricaClient::getServiceUrl()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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