Model::set()   B
last analyzed

Complexity

Conditions 9
Paths 7

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 11.3597

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 9
cts 13
cp 0.6923
rs 8.0555
c 0
b 0
f 0
cc 9
nc 7
nop 2
crap 11.3597
1
<?php
2
/**
3
 * Class Model
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 Exception;
13
use Lan\Ebs\Sdk\Client;
14
use Lan\Ebs\Sdk\Common;
15
16
/**
17
 *  Абстрактный класс моделей
18
 *
19
 * @package      Lan\Ebs
20
 * @subpackage   Sdk
21
 * @category     Classes
22
 */
23
abstract class Model implements Common
24
{
25
    const MESSAGE_ID_REQUIRED = 'Id is required';
26
    const MESSAGE_ID_CAN_NOT_CHANGED = 'Id can not be changed';
27
28
    /**
29
     * Инстанс клиента API
30
     *
31
     * @var Client
32
     */
33
    private $client;
34
35
    /**
36
     * Имена полей, подлежаших получению через API
37
     *
38
     * @var array
39
     */
40
    private $fields = array();
41
42
    /**
43
     * Данные модели
44
     *
45
     * @var array
46
     */
47
    private $data = array();
48
49
    /**
50
     * Идентификатор модели
51
     *
52
     * @var null
53
     */
54
    private $id = null;
55
56
    /**
57
     * Статус последнего обращения по API
58
     *
59
     * @var int
60
     */
61
    private $lastStatus = 0;
62
63
    /**
64
     * Конструктор модели
65
     *
66
     * @param Client $client Инстанс клиента
67
     * @param array $fields Поля для выборки
68
     *
69
     * Пример:
70
     * ```php
71
     *      $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
72
     *
73
     *      $client = new Client($token); // инициализация клиента
74
     *
75
     *      $book = new Book($client, []); // инициализация модели книг
76
     * ```
77
     *
78
     * @throws Exception
79
     *
80
     * @see Article::__construct
81
     * @see Book::__construct
82
     * @see Issue::__construct
83
     * @see Journal::__construct
84
     * @see User::__construct
85
     */
86 4
    public function __construct(Client $client, array $fields)
87
    {
88 4
        if (!$client) {
89
            throw new Exception('Клиент не инициализирован');
90
        }
91
92 4
        if (!is_array($fields)) {
93
            throw new Exception('Fields for model of collection mast be array');
94
        }
95
96 4
        $this->client = $client;
97 4
        $this->fields = $fields;
98 4
    }
99
100
    /**
101
     * Загружаемые поля модели
102
     *
103
     * Те поля модели, которые будут получены по API
104
     *
105
     * @return array
106
     */
107
    public function getFields()
108
    {
109
        return $this->fields;
110
    }
111
112
    /**
113
     * Добавление новой записи по API
114
     *
115
     * Создание новой сущности
116
     *
117
     * @param array $data Устанавливаемые данные модели
118
     *
119
     * ```php
120
     * $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
121
     *
122
     * $client = new Client($token); // инициализация клиента
123
     *
124
     * $user = new User($client);
125
     * $user->post([
126
     *      'login' => 'new_user_login',
127
     *      'password' => 'new_user_password',
128
     *      'fio' => 'new_user_fio'
129
     * ]);
130
     * ```
131
     *
132
     * @return $this Возвращает модель с данными и вновь созданным идентификатором
133
     *
134
     * @throws Exception
135
     */
136 1
    public function post(array $data = array())
137
    {
138 1
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__), $data);
139
140
        $this->set($response['data'], $response['status']);
141
142
        return $this;
143
    }
144
145
    /**
146
     * Получение инстанса клиента
147
     *
148
     * @return Client
149
     */
150 1
    protected function getClient()
151
    {
152 1
        return $this->client;
153
    }
154
155
    /**
156
     * Установка данных модели
157
     *
158
     * Изменение данных модели
159
     *
160
     * @param  array $data Данные модели
161
     * @param  int $status Статус полученных данных
162
     *
163
     * ```php
164
     * $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
165
     *
166
     * $client = new Client($token); // инициализация клиента
167
     *
168
     * $user = new User($client);
169
     * $user->set([
170
     *      'login' => 'new_user_login',
171
     *      'password' => 'new_user_password',
172
     *      'fio' => 'new_user_fio'
173
     * ]);
174
     * $user->post();
175
     * ```
176
     *
177
     * @return $this Возвращает модель с данными и вновь созданным идентификатором
178
     *
179
     * @throws Exception
180
     */
181 1
    public function set(array $data, $status = null)
182
    {
183 1
        if (empty($data)) {
184
            return $this;
185
        }
186
187 1
        if (empty($data['id']) && empty($this->getId())) {
188
            throw new Exception(Model::MESSAGE_ID_REQUIRED);
189
        }
190
191 1
        if (!empty($data['id']) && !empty($this->getId()) && $data['id'] != $this->getId()) {
192
            throw new Exception(Model::MESSAGE_ID_CAN_NOT_CHANGED);
193
        }
194
195 1
        if (!empty($data['id'])) {
196 1
            $this->setId($data['id']);
197
        }
198
199 1
        $this->data = array_merge((array)$this->data, $data);
200
201 1
        if ($status) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $status of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
202
            $this->lastStatus = $status;
203
        }
204
205 1
        return $this;
206
    }
207
208
    /**
209
     * Получение идентификатора модели
210
     *
211
     * @return int
212
     */
213 3
    public function getId()
214
    {
215 3
        return $this->id;
216
    }
217
218
    /**
219
     * Установка идентификатора модели
220
     *
221
     * @param int $id Идентификатор модели
222
     *
223
     * @return int
224
     *
225
     * @throws Exception
226
     */
227 1
    public function setId($id)
228
    {
229 1
        return $this->id = $id;
0 ignored issues
show
Documentation Bug introduced by
It seems like $id of type integer is incompatible with the declared type null of property $id.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
230
    }
231
232
    /**
233
     * Обновление записи по API
234
     *
235
     * @param array $data Обновляемые данные
236
     *
237
     * ```php
238
     * $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
239
     *
240
     * $client = new Client($token); // инициализация клиента
241
     *
242
     * $user = new User($client);
243
     * $user->setId($testUserPk);
244
     * $user->put([
245
     *      'fio' => 'user_new_fio',
246
     *      'password' => 'user_new_password',
247
     * ]);
248
     * ```
249
     *
250
     * @return $this Возвращает модель с данными и вновь созданным идентификатором
251
     *
252
     * @throws Exception
253
     */
254 View Code Duplication
    public function put(array $data = array())
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...
255
    {
256
        $this->set($data);
257
258
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__, array($this->getId())), $data);
259
260
        $this->set($response['data'], $response['status']);
261
262
        return $this;
263
    }
264
265
    /**
266
     * Удаление модели
267
     *
268
     * @param int $id Идентификатор модели
269
     *
270
     * ```php
271
     * $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
272
     *
273
     * $client = new Client($token); // инициализация клиента
274
     *
275
     * $user = new User($client);
276
     * $user->delete($testUserPk);
277
     * ```
278
     *
279
     * @return $this Возвращает модель с данными и вновь созданным идентификатором
280
     *
281
     * @throws Exception
282
     */
283 View Code Duplication
    public function delete($id = null)
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...
284
    {
285
        if (empty($this->getId())) {
286
            $this->set(array('id' => $id));
287
        }
288
289
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__, array($this->getId())));
290
291
        $this->set($response['data'], $response['status']);
292
293
        return $this;
294
    }
295
296
    /**
297
     * Магический Get
298
     *
299
     * @param mixed $name Имя поля
300
     *
301
     * @return mixed
302
     *
303
     * @throws Exception
304
     */
305
    public function __get($name)
306
    {
307
        $data = $this->get();
308
309
        if (!array_key_exists($name, $data)) {
310
            throw new Exception('Поле ' . $name . ' не указано при создвнии объекта модели ' . get_class($this) . ' (см. 2-й аргумент fields)');
311
        }
312
313
        return $data[$name];
314
    }
315
316
    /**
317
     * Получение метаданных по идентификатору модели
318
     *
319
     * @param int $id Идентификатор модели
320
     *
321
     * ```php
322
     * $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
323
     *
324
     * $client = new Client($token); // инициализация клиента
325
     *
326
     * $user = new User($client);
327
     * $userData = $user->get($testUserPk);
328
     * ```
329
     *
330
     * @return array Получение метаданных модели
331
     *
332
     * @throws Exception
333
     */
334 2
    public function get($id = null)
335
    {
336 2
        if ($id === null && $this->getId() !== null) {
337
            return $this->data;
338
        }
339
340 2
        if (!$id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
341 2
            throw new Exception(Model::MESSAGE_ID_REQUIRED);
342
        }
343
344
        $this->setId($id);
345
346
        $params = $this->fields ? ['fields' => implode(',', $this->fields)] : [];
347
348
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__, array($this->getId())), $params);
349
350
        $this->set($response['data'], $response['status']);
351
352
        return $this->data;
353
    }
354
}