Completed
Push — master ( 1f7ab5...0b80d4 )
by Denis
05:55
created

Model::post()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
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 = [];
41
42
    /**
43
     * Данные модели
44
     *
45
     * @var array
46
     */
47
    private $data = [];
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
     * @throws Exception
70
     */
71 10
    public function __construct(Client $client, array $fields)
72
    {
73 10
        if (!$client) {
74
            throw new Exception('Клиент не инициализирован');
75
        }
76
77 10
        if (!is_array($fields)) {
78
            throw new Exception('Fields for model of collection mast be array');
79
        }
80
81 10
        $this->client = $client;
82 10
        $this->fields = $fields;
83 10
    }
84
85
    /**
86
     * Загружаемые поля модели
87
     *
88
     * @return array
89
     */
90
    public function getFields()
91
    {
92
        return $this->fields;
93
    }
94
95
    /**
96
     * Добавление новой записи по API
97
     *
98
     * @param array $data Устанавливаемые данные модели
99
     *
100
     * @return $this
101
     *
102
     * @throws Exception
103
     */
104 1
    public function post(array $data)
105
    {
106 1
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__), $data);
107
108 1
        $this->set($response['data'], $response['status']);
109
110 1
        return $this;
111
    }
112
113
    /**
114
     * Получение инстанса клиента
115
     *
116
     * @return Client
117
     */
118 5
    protected function getClient()
119
    {
120 5
        return $this->client;
121
    }
122
123
    /**
124
     * Установка данных модели
125
     *
126
     * @param  array $data Данные модели
127
     * @param  int $status Статус полученных данных
128
     *
129
     * @return $this
130
     *
131
     * @throws Exception
132
     */
133 10
    public function set(array $data, $status = null)
134
    {
135 10
        if (empty($data['id']) && empty($this->getId())) {
136 2
            throw new Exception(Model::MESSAGE_ID_REQUIRED);
137
        }
138
139 8
        if (!empty($data['id']) && !empty($this->getId()) && $data['id'] != $this->getId()) {
140
            throw new Exception(Model::MESSAGE_ID_CAN_NOT_CHANGED);
141
        }
142
143 8
        if (!empty($data['id'])) {
144 8
            $this->setId($data['id']);
145
        }
146
147 8
        $this->data = array_merge((array)$this->data, $data);
148
149 8
        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...
150 5
            $this->lastStatus = $status;
151
        }
152
153 8
        return $this;
154
    }
155
156
    /**
157
     * Получение идентификатора модели
158
     *
159
     * @return int
160
     */
161 10
    public function getId()
162
    {
163 10
        return $this->id;
164
    }
165
166
    /**
167
     * Установка идентификатора модели
168
     *
169
     * @param int $id Идентификатор модели
170
     *
171
     * @return int
172
     *
173
     * @throws Exception
174
     */
175 8
    public function setId($id)
176
    {
177 8
        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...
178
    }
179
180
    /**
181
     * Обновление записи по API
182
     *
183
     * @param array $data Обновляемые данные
184
     *
185
     * @return $this
186
     *
187
     * @throws Exception
188
     */
189 1
    public function put(array $data)
190
    {
191 1
        $this->set($data);
192
193 1
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__, [$this->getId()]), $data);
194
195 1
        $this->set($response['data'], $response['status']);
196
197 1
        return $this;
198
    }
199
200
    /**
201
     * Удаление модели
202
     *
203
     * @param int $id Идентификатор модели
204
     *
205
     * @return $this
206
     *
207
     * @throws Exception
208
     */
209 1
    public function delete($id = null)
210
    {
211 1
        if (empty($this->getId())) {
212
            $this->set(['id' => $id]);
213
        }
214
215 1
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__, [$this->getId()]));
216
217 1
        $this->set($response['data'], $response['status']);
218
219 1
        return $this;
220
    }
221
222
    /**
223
     * Магический Get
224
     *
225
     * @param mixed $name Имя поля
226
     *
227
     * @return mixed
228
     *
229
     * @throws Exception
230
     */
231 4
    public function __get($name)
232
    {
233 4
        $data = $this->get();
234
235 4
        if (!array_key_exists($name, $data)) {
236
            throw new Exception('Поле ' . $name . ' не указано при создвнии объекта модели ' . get_class($this) . ' (см. 2-й аргумент)');
237
        }
238
239 4
        return $data[$name];
240
    }
241
242
    /**
243
     * Получение метаданных по идентификатору модели
244
     *
245
     * @param int $id Идентификатор модели
246
     *
247
     * @return array
248
     *
249
     * @throws Exception
250
     */
251 5
    public function get($id = null)
252
    {
253 5
        if ($id === null && $this->getId() !== null) {
254 4
            return $this->data;
255
        }
256
257 3
        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...
258 2
            throw new Exception(Model::MESSAGE_ID_REQUIRED);
259
        }
260
261 3
        $this->setId($id);
262
263 3
        $params = $this->fields ? ['fields' => implode(',', $this->fields)] : [];
264
265 3
        $response = $this->getClient()->getResponse($this->getUrl(__FUNCTION__, [$this->getId()]), $params);
266
267 2
        $this->set($response['data'], $response['status']);
268
269 2
        return $this->data;
270
    }
271
}