Completed
Push — master ( e8241e...60d0c3 )
by
unknown
04:24 queued 02:47
created

Collection::getFullCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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