Completed
Pull Request — master (#155)
by Alexander
05:35
created

MetricaClient   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 230
Duplicated Lines 25.65 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 79.17%

Importance

Changes 9
Bugs 2 Features 4
Metric Value
wmc 22
c 9
b 2
f 4
lcom 1
cbo 10
dl 59
loc 230
ccs 76
cts 96
cp 0.7917
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getServiceUrl() 0 12 3
A sendGetRequest() 6 23 3
B getNextPartOfList() 6 26 3
A sendPostRequest() 16 16 1
A sendPutRequest() 16 16 1
A sendDeleteRequest() 15 15 1
D sendRequest() 0 41 9

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
     */
45 57
    public function __construct($token = '')
46
    {
47 57
        $this->setAccessToken($token);
48 57
    }
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
     */
58 29
    public function getServiceUrl($resource = '', $params = [])
59
    {
60 29
        $format = $resource === '' ? '' : '.json';
61 29
        $url = $this->serviceScheme . '://' . $this->serviceDomain . '/'
62 29
            . $resource . $format . '?oauth_token=' . $this->getAccessToken();
63
64 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...
65 2
            $url .= '&' . http_build_query($params);
66 2
        }
67
68 29
        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
     * @throws TooManyRequestsException
84
     * @throws UnauthorizedException
85
     */
86 27
    protected function sendRequest($method, $uri, array $options = [])
87
    {
88
        try {
89 27
            $response = $this->getClient()->request($method, $uri, $options);
90 27
        } catch (ClientException $ex) {
91 5
            $result = $ex->getResponse();
92 5
            $code = $result->getStatusCode();
93 5
            $message = $result->getReasonPhrase();
94
95 5
            $body = $result->getBody();
96 5
            if ($body) {
97 5
                $jsonBody = json_decode($body);
98 5
                if ($jsonBody && isset($jsonBody->message)) {
99 1
                    $message = $jsonBody->message;
100 1
                }
101 5
            }
102
103 5
            if ($code === 400) {
104 1
                throw new BadRequestException($message);
105
            }
106
107 4
            if ($code === 403) {
108 1
                throw new ForbiddenException($message);
109
            }
110
111 3
            if ($code === 401) {
112 1
                throw new UnauthorizedException($message);
113
            }
114
115 2
            if ($code === 429) {
116 1
                throw new TooManyRequestsException($message);
117
            }
118
119 1
            throw new MetricaException(
120 1
                'Service responded with error code: "' . $code . '" and message: "' . $message . '"',
121
                $code
122 1
            );
123
        }
124
125 22
        return $response;
126
    }
127
128
    /**
129
     * Send GET request to API resource
130
     *
131
     * @param string $resource
132
     * @param array $params
133
     * @return array
134
     */
135 6
    protected function sendGetRequest($resource, $params = [])
136
    {
137 6
        $response = $this->sendRequest(
138 6
            'GET',
139 6
            $this->getServiceUrl($resource, $params),
140
            [
141
                'headers' => [
142 6
                    'Accept' => 'application/x-yametrika+json',
143 6
                    'Content-Type' => 'application/x-yametrika+json',
144
                ]
145 6
            ]
146 6
        );
147
148 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
149
150 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...
151
            $url = $decodedResponseBody['links']['next'];
152
            unset($decodedResponseBody['rows']);
153
            unset($decodedResponseBody['links']);
154
            return $this->getNextPartOfList($url, $decodedResponseBody);
155
        }
156 1
        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
            unset($mergedDecodedResponseBody['rows']);
186
            unset($mergedDecodedResponseBody['links']);
187
            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
        }
189
190
        return $mergedDecodedResponseBody;
191
    }
192
193
    /**
194
     * Send POST request to API resource
195
     *
196
     * @param string $resource
197
     * @param array $params
198
     * @return array
199
     */
200 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...
201
    {
202 7
        $response = $this->sendRequest(
203 7
            'POST',
204 7
            $this->getServiceUrl($resource),
205
            [
206
                'headers' => [
207 7
                    'Accept' => 'application/x-yametrika+json',
208 7
                    'Content-Type' => 'application/x-yametrika+json',
209 7
                ],
210
                'json' => $params
211 7
            ]
212 7
        );
213
214 7
        return $this->getDecodedBody($response->getBody());
215
    }
216
217
    /**
218
     * Send PUT request to API resource
219
     *
220
     * @param string $resource
221
     * @param array $params
222
     * @return array
223
     */
224 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...
225
    {
226 7
        $response = $this->sendRequest(
227 7
            'PUT',
228 7
            $this->getServiceUrl($resource),
229
            [
230
                'headers' => [
231 7
                    'Accept' => 'application/x-yametrika+json',
232 7
                    'Content-Type' => 'application/x-yametrika+json',
233 7
                ],
234
                'json' => $params
235 7
            ]
236 7
        );
237
238 7
        return $this->getDecodedBody($response->getBody());
239
    }
240
241
    /**
242
     * Send DELETE request to API resource
243
     *
244
     * @param string $resource
245
     * @return array
246
     */
247 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...
248
    {
249 7
        $response = $this->sendRequest(
250 7
            'DELETE',
251 7
            $this->getServiceUrl($resource),
252
            [
253
                'headers' => [
254 7
                    'Accept' => 'application/x-yametrika+json',
255 7
                    'Content-Type' => 'application/x-yametrika+json',
256
                ]
257 7
            ]
258 7
        );
259
260 7
        return $this->getDecodedBody($response->getBody());
261
    }
262
}
263