GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 90b2df...112e43 )
by Evgeny
12s
created

AbstractList::getMetaKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace SimaLand\API;
4
5
use GuzzleHttp\Psr7\Response;
6
use SimaLand\API\Rest\Client;
7
use SimaLand\API\Rest\Request;
8
9
/**
10
 * Абстрактный класс для загрузки данных сущности.
11
 *
12
 * Класс реализует интерфейс Iterator.
13
 */
14
abstract class AbstractList extends Object implements \Iterator
15
{
16
    /**
17
     * Кол-во потоков.
18
     *
19
     * @var int
20
     */
21
    public $countThreads = 5;
22
23
    /**
24
     * GET параметр отвечающий за поток.
25
     *
26
     * @var string
27
     */
28
    public $keyThreads = 'page';
29
30
    /**
31
     * Ключ альтернативной пагинации.
32
     *
33
     * @var string
34
     */
35
    public $keyAlternativePagination = 'id-greater-than';
36
37
    /**
38
     * SimaLand кдиент для запросов.
39
     *
40
     * @var \SimaLand\API\Rest\Client
41
     */
42
    private $client;
43
44
    /**
45
     * Список запросов.
46
     *
47
     * @var Request[]
48
     */
49
    private $requests = [];
50
51
    /**
52
     * Список данных полученные по API.
53
     *
54
     * @var array
55
     */
56
    private $values = [];
57
58
    /**
59
     * GET параметры запроса.
60
     *
61
     * @var array
62
     */
63
    public $getParams = [];
64
65
    /**
66
     * Ключ текущей записи.
67
     *
68
     * @var int
69
     */
70
    private $key;
71
72
    /**
73
     * Текущая запись.
74
     *
75
     * @var mixed
76
     */
77
    private $current;
78
79
    /**
80
     * @param Client $client
81
     * @param array $options
82
     */
83
    public function __construct(Client $client, array $options = [])
84
    {
85
        $this->client = $client;
86
        parent::__construct($options);
87
    }
88
89
    /**
90
     * Получить наименование сущности.
91
     *
92
     * @return string
93
     */
94
    abstract public function getEntity();
95
96
    /**
97
     * Добавить get параметры.
98
     *
99
     * @param array $params
100
     * @return AbstractList
101
     */
102
    public function addGetParams(array $params)
103
    {
104
        $this->getParams = array_merge($this->getParams, $params);
105
        return $this;
106
    }
107
108
    /**
109
     * Назначить следующию страницу запросу.
110
     *
111
     * @param Request $request
112
     * @param Record|null $record
113
     */
114
    public function assignPage(Request &$request, Record $record = null)
115
    {
116
        $currentPage = 1;
117
        if (!is_array($request->getParams)) {
118
            $request->getParams = (array)$request->getParams;
119
        }
120
        if (isset($request->getParams[$this->keyThreads])) {
121
            $currentPage = (int)$request->getParams[$this->keyThreads];
122
        }
123
        $request->getParams[$this->keyThreads] = $currentPage + $this->countThreads;
124
    }
125
126
    /**
127
     * Назначить номер потока для запроса.
128
     *
129
     * @param Request $request
130
     * @param int $number
131
     */
132
    public function assignThreadsNumber(Request &$request, $number = 0)
133
    {
134
        if (!is_array($request->getParams)) {
135
            $request->getParams = (array)$request->getParams;
136
        }
137
        if (!isset($request->getParams[$this->keyThreads])) {
138
            $request->getParams[$this->keyThreads] = 1;
139
        }
140
        $request->getParams[$this->keyThreads] += $number;
141
    }
142
143
    /**
144
     * Наименование ключа содержащего набора данных сущности.
145
     *
146
     * @return string
147
     */
148
    public function getCollectionKey()
149
    {
150
        return 'items';
151
    }
152
153
    /**
154
     * Наименование ключа содержащего мета данные.
155
     *
156
     * @return string
157
     */
158
    public function getMetaKey()
159
    {
160
        return '_meta';
161
    }
162
163
    /**
164
     * Палучить набор данных сущности.
165
     *
166
     * @return Response[]
167
     * @throws \Exception
168
     */
169
    public function get()
170
    {
171
        return $this->client->batchQuery($this->getRequests());
172
    }
173
174
    /**
175
     * Установить запросы к API.
176
     *
177
     * @param Request[] $requests
178
     * @throws \Exception
179
     */
180
    public function setRequests(array $requests)
181
    {
182
        $this->requests = [];
183
        foreach ($requests as $request) {
184
            if (!$request instanceof Request) {
185
                throw new \Exception('Request must be implement "\SimaLand\API\Rest\Request"');
186
            }
187
            $this->requests[] = $request;
188
        }
189
    }
190
191
    /**
192
     * Получить запросы к API.
193
     *
194
     * @return array|Rest\Request[]
195
     */
196
    public function getRequests()
197
    {
198
        if (empty($this->requests)) {
199
            $requests = [];
200
            if (!is_null($this->keyThreads) && $this->countThreads > 1) {
201
                for ($i = 0; $i < $this->countThreads; $i++) {
202
                    $requests[$i] = new Request([
203
                        'entity' => $this->getEntity(),
204
                        'getParams' => $this->getParams,
205
                    ]);
206
                    $this->assignThreadsNumber($requests[$i], $i);
207
                }
208
            } else {
209
                $requests[] = new Request([
210
                    'entity' => $this->getEntity(),
211
                    'getParams' => $this->getParams,
212
                ]);
213
            }
214
            $this->requests = $requests;
215
        }
216
        return $this->requests;
217
    }
218
219
    /**
220
     * @inheritdoc
221
     */
222
    public function current()
223
    {
224
        return $this->current;
225
    }
226
227
    /**
228
     * @inheritdoc
229
     */
230
    public function next()
231
    {
232
        if (empty($this->values)) {
233
            $this->getData();
234
        }
235
        $this->current = array_shift($this->values);
236
    }
237
238
    /**
239
     * @inheritdoc
240
     */
241
    public function key()
242
    {
243
        return $this->key++;
244
    }
245
246
    /**
247
     * @inheritdoc
248
     */
249
    public function valid()
250
    {
251
        return !empty($this->current);
252
    }
253
254
    /**
255
     * @inheritdoc
256
     */
257
    public function rewind()
258
    {
259
        $this->values = [];
260
        $this->current = null;
261
        $this->key = 0;
262
        $this->next();
263
    }
264
265
    /**
266
     * Получить тело ответа от API.
267
     *
268
     * @param Response $response
269
     * @return bool
270
     * @throws \Exception
271
     */
272
    private function getBody(Response $response)
273
    {
274
        $body = json_decode($response->getBody(), true);
275
        $statusCode = $response->getStatusCode();
276
        if (($statusCode < 200 || $statusCode >= 300) && $statusCode != 404) {
277
            if ($body && isset($body['message'])) {
278
                $message = $body['message'];
279
            } else {
280
                $message = $response->getReasonPhrase();
281
            }
282
            throw new \Exception($message, $statusCode);
283
        } elseif (
284
            $statusCode == 404 ||
285
            !$body ||
286
            ($body && !isset($body[$this->getCollectionKey()]))
287
        ) {
288
            return false;
289
        }
290
        return $body;
291
    }
292
293
    /**
294
     * Получить набор данных от API.
295
     *
296
     * @throws \Exception
297
     */
298
    private function getData()
299
    {
300
        $responses = $this->get();
301
        $collectionKey = $this->getCollectionKey();
302
        $metaKey = $this->getMetaKey();
303
        $requests = $this->getRequests();
304
        $record = null;
305
        foreach ($responses as $key => $response) {
306
            $body = $this->getBody($response);
307
            if (!$body) {
308
                unset($requests[$key]);
309
                continue;
310
            }
311
            foreach ($body[$collectionKey] as $item) {
312
                $record = new Record([
313
                    'data' => $item,
314
                    'meta' => isset($body[$metaKey]) ? $body[$metaKey] : null,
315
                ]);
316
                $this->values[] = $record;
317
            }
318
            if (!is_null($record)) {
319
                $this->assignPage($requests[$key], $record);
320
            }
321
        }
322
        $this->setRequests($requests);
323
    }
324
}
325