Completed
Push — master ( 0fb1a1...c53a6f )
by Denis
02:17
created

Collection::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Class BookCollection
4
 *
5
 * @author       Denis Shestakov <[email protected]>
6
 * @copyright    Copyright (c) 2017, Lan Publishing
7
 * @license      MIT
8
 */
9
10
namespace Lan\Ebs\Sdk\Classes;
11
12
use ArrayObject;
13
use Exception;
14
use Lan\Ebs\Sdk\Client;
15
use Lan\Ebs\Sdk\Common;
16
use ReflectionClass;
17
18
/**
19
 * Абстрактный класс для всех коллекций (+ итерируемый)
20
 *
21
 * @package      Lan\Ebs
22
 * @subpackage   Sdk
23
 * @category     Classes
24
 */
25
abstract class Collection extends ArrayObject implements Common
26
{
27
    /**
28
     * Инстанс клиента API
29
     *
30
     * @var Client
31
     */
32
    private $client;
33
34
    /**
35
     * Флаг, сигнализирующий что коллекция загружена
36
     *
37
     * @var int
38
     */
39
    private $loadStatus = 0;
40
41
    /**
42
     * Имена полей, подлежаших получению через API
43
     *
44
     * @var array
45
     */
46
    private $fields = [];
47
48
    /**
49
     * Класс модели
50
     *
51
     * @var Model|string
52
     */
53
    private $class = null;
54
55
    /**
56
     * Лимит получаемых моделей коллекции через API
57
     *
58
     * @var int
59
     */
60
    private $limit = null;
61
62
    /**
63
     * Смещение выборки моделей через API
64
     *
65
     * @var int
66
     */
67
    private $offset = null;
68
69
    /**
70
     * Всего элементов без учета лимита
71
     *
72
     * @var int
73
     */
74
    private $fullCount = null;
75
76
    /**
77
     * Конструктор коллекции
78
     *
79
     * @param Client $client Инстанс клиента
80
     * @param array $fields Поля для выборки
81
     * @param string $class Класс модели
82
     * @param int $limit Лимит выборки
83
     * @param int $offset Смещение выборки
84
     *
85
     * @throws Exception
86
     */
87 3
    public function __construct(Client $client, array $fields, $class, $limit, $offset)
88
    {
89 3
        if (!$client) {
90
            throw new Exception('Клиент не инициализирован');
91
        }
92
93 3
        if (!is_array($fields)) {
94
            throw new Exception('Fields for model of collection mast be array');
95
        }
96
97 3
        $reflectionClass = new ReflectionClass($class);
98
99 3
        if (!$reflectionClass->isSubclassOf(Model::class)) {
100
            throw new Exception('Class of model collection not subclass for Model');
101
        }
102
103 3
        $this->client = $client;
104 3
        $this->fields = $fields;
105 3
        $this->class = $class;
106
107 3
        $this->setLimit($limit);
108 3
        $this->setOffset($offset);
109 3
    }
110
111
    /**
112
     * Установка лимита выборки
113
     *
114
     * @param int $limit Значение лимита выборки
115
     *
116
     * @throws Exception
117
     */
118 3
    public function setLimit($limit)
119
    {
120 3
        $this->limit = $limit;
121
122 3
        if ($this->loadStatus == 200) {
123
            $this->load(true);
124
        }
125 3
    }
126
127
    /**
128
     * Загрузка коллекции
129
     *
130
     * @param bool $force Заново загружать коллекцию даже если она загружена ранее
131
     *
132
     * @return $this
133
     *
134
     * @throws Exception
135
     */
136 3
    public function load($force = false)
137
    {
138 3
        if ($this->loadStatus == 200 && !$force) {
139
            return $this;
140
        }
141
142
        $params = [
143 3
            'limit' => $this->limit,
144 3
            'offset' => $this->offset
145
        ];
146
147 3
        if (!empty($this->fields)) {
148
            $params['fields'] = implode(',', (array)$this->fields);
149
        }
150
151 3
        $response = $this->client->getResponse($this->getUrl(__FUNCTION__), $params);
152
153
        $this->exchangeArray($response['data']);
154
155
        $this->loadStatus = $response['status'];
156
157
        $this->fullCount = $response['count'];
158
159
        unset($response);
160
161
        return $this;
162
    }
163
164
    /**
165
     * Установка смещения выборки
166
     *
167
     * @param int $offset Значение смещения выборки
168
     *
169
     * @throws Exception
170
     */
171 3
    public function setOffset($offset)
172
    {
173 3
        $this->offset = $offset;
174
175 3
        if ($this->loadStatus == 200) {
176
            $this->load(true);
177
        }
178 3
    }
179
180
    /**
181
     * Получение количества всех элементов без учета лимита
182
     *
183
     * @return int
184
     *
185
     * @throws Exception
186
     */
187
    public function getFullCount()
188
    {
189
        $this->load();
190
191
        return $this->fullCount;
192
    }
193
194
    /**
195
     * Получение нового инстанса итератора коллекции
196
     *
197
     * @return CollectionIterator
198
     */
199
    public function getIterator()
200
    {
201
        return new CollectionIterator($this);
202
    }
203
204
    /**
205
     * Количество моделей в коллекции
206
     *
207
     * @return int
208
     *
209
     * @throws Exception
210
     */
211 2
    public function count()
212
    {
213 2
        $this->load();
214
215
        return parent::count();
216
    }
217
218
    /**
219
     * Получение коллекции в виде массива
220
     *
221
     * @return array
222
     *
223
     * @throws Exception
224
     */
225
    public function getData()
226
    {
227
        $this->load();
228
229
        return $this->getArrayCopy();
230
    }
231
232
    /**
233
     * Получение первой модели в коллекции
234
     *
235
     * @return Model
236
     *
237
     * @throws Exception
238
     */
239 1
    public function reset()
240
    {
241 1
        $this->load();
242
243
        return $this->createModel(reset($this));
244
    }
245
246
    /**
247
     * Создание модели по переданным данным
248
     *
249
     * @param array $data Данные для создания модели
250
     *
251
     * @return Model
252
     *
253
     * @throws Exception
254
     */
255
    public function createModel(array $data = null)
256
    {
257
        $class = $this->class;
258
259
        /**
260
         * @var Model $model
261
         */
262
        $model = new $class($this->client, $this->fields);
263
264
        $model->set($data === null ? current($this) : $data);
265
266
        return $model;
267
    }
268
269
    /**
270
     * Получение последней модели в коллекции
271
     *
272
     * @return Model
273
     *
274
     * @throws Exception
275
     */
276
    public function end()
277
    {
278
        $this->load();
279
280
        return $this->createModel(end($this));
281
    }
282
283
    /**
284
     * Получение инстанса клиента
285
     *
286
     * @return Client
287
     */
288
    protected function getClient()
289
    {
290
        return $this->client;
291
    }
292
}