Completed
Push — master ( c14aad...5ba59a )
by Denis
06:56
created

Collection::setOffset()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

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