-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponse.php
More file actions
366 lines (307 loc) · 8.64 KB
/
Copy pathResponse.php
File metadata and controls
366 lines (307 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php declare(strict_types=1);
/**
* @name: knock-knock
* @author Andrey and_y87 Kidin
* @description Компонент содержащий параметры ответа
* @homepage: https://github.com/andy87/KnockKnock
* @license CC BY-SA 4.0 http://creativecommons.org/licenses/by-sa/4.0/
* @date 2024-05-27
* @version 1.3.2
*/
namespace andy87\knock_knock\core;
use andy87\knock_knock\interfaces\{RequestInterface, ResponseInterface};
use andy87\knock_knock\exception\{ParamNotFoundException, ParamUpdateException};
/**
* Предоставляет данные ответа, преобразование JSON и диагностику ошибок.
*
* @package andy87\knock_knock\query
*
* @property-read int $httpCode
* @property-read mixed $content
*
* @property-read Request $request
*
* @property-read array $errors
*
* @see \andy87\knock_knock\tests\core\ResponseTest
*/
class Response implements ResponseInterface
{
/** @var array $_errors */
protected array $_errors = [];
/** @var bool $isArray */
protected bool $isArray = false;
/**
* Response constructor.
*
* @param mixed $_data
* @param int $_httpCode
* @param ?Request $_request
*
* @tag #response #constructor #response
*/
public function __construct(
protected mixed $_data,
protected int $_httpCode,
protected ?Request $_request = null
){}
/**
* Магия для получения read-only свойств
*
* @param string $name
*
* @return mixed
*
* @throws ParamNotFoundException
*
* Test: @see ResponseTest::testMagicGet()
*
* @tag #response #magic #get
*/
public function __get(string $name): mixed
{
return match ($name) {
self::HTTP_CODE => $this->getterHttpCode(),
self::CONTENT => $this->getterData(),
'request' => $this->getterRequest(),
RequestInterface::SETUP_CURL_OPTIONS => $this->request->curlOptions,
RequestInterface::SETUP_CURL_INFO => $this->request->curlInfo,
'errors' => $this->getterErrors(),
default => throw new ParamNotFoundException("Свойство `$name` не найдено в классе " . __CLASS__),
};
}
// === PUBLIC ===
/**
* Установка HTTP кода ответа
*
* @param int $httpCode
*
* @return void
*
* @throws ParamUpdateException|ParamNotFoundException
*
* Test: @see ResponseTest::testSetupHttpCode()
*
* @tag #response #setter #httpCode
*/
public function setupHttpCode(int $httpCode): void
{
$this->setter('_httpCode', $httpCode);
}
/**
* Установка данных ответа
*
* @param string $data
*
* @return void
*
* @throws ParamUpdateException|ParamNotFoundException
*
* Test: @see ResponseTest::setupData()
*
* @tag #response #setter #data
*/
public function setupData(string $data): void
{
$this->setter('_data', $data);
}
/**
* Установка объекта запроса
*
* @param Request $request
*
* @return void
*
* @throws ParamUpdateException|ParamNotFoundException
*
* Test: @see ResponseTest::testSetupRequest()
*
* @tag #response #setter #request
*/
public function setupRequest(Request $request): void
{
$this->setter('_request', $request);
}
/**
* Замена значений в свойствах
*
* @param string $key
* @param mixed $value
*
* @return Response
*
* @throws ParamNotFoundException
*
* Test: @see ResponseTest::testReplace()
*
* @tag #response #replace #content #httpCode
*/
public function replace(string $key, mixed $value): Response
{
match ($key) {
self::HTTP_CODE => $this->_httpCode = $value,
self::CONTENT => $this->_data = $value,
default => throw new ParamNotFoundException('Bad key'),
};
return $this;
}
/**
* Задаёт ответ в виде массива
*
* @return $this
*
* Test: @see ResponseTest::testAsArray()
*
* @tag #response #array #set
*/
public function asArray(): self
{
$this->isArray = true;
return $this;
}
// --- Errors ---
/**
* Добавляет ошибку до завершения запроса; для ответа без запроса также доступно.
*
* @param string $errorMessage Диагностическое сообщение без изменения формата errors.
*
* @return $this
*
* Test: @see ResponseTest::testGetErrors()
*
* @tag #response #error #add
*/
public function addError(string $errorMessage): self
{
if ($this->_request === null || !$this->_request->statusIsComplete()) {
$this->_errors[] = $errorMessage;
}
return $this;
}
/**
* Получение Trace лог истории вызовов методов
*
* @return array
*
* Test: @see ResponseTest::testGetErrors()
*
* @tag #response #getter #error
*/
private function getterErrors(): array
{
return $this->_errors;
}
/**
* Валидация ошибок, если ошибок нет, то возвращает true
*
* @return bool
*
* Test: @see ResponseTest::testValidate()
*
* @tag #response #validate #error
*/
public function validate(): bool
{
return empty($this->_errors);
}
// === PRIVATE ===
// --- Setters ---
/**
* Общий метод для установки значений в свойства
*
* @param string $key
* @param mixed $value
*
* @return void
*
* @throws ParamUpdateException|ParamNotFoundException
*
* @tag #response #setter
*/
private function setter(string $key, mixed $value): void
{
if (isset($this->$key)) {
$error = "`$key` is already set";
$this->addError($error);
throw new ParamUpdateException($error);
}
if ($this->_request && $this->_request->statusIsComplete()) {
throw new ParamNotFoundException("Запрос уже был отправлен: нельзя изменить данные ответа `$key`");
}
$this->$key = $value;
}
// --- Getters ---
/**
* Возвращает объект запроса
*
* @return Request
*
* Test: @see ResponseTest::testSetupRequest()
*
* @tag #response #getter #request
*/
private function getterRequest(): Request
{
return $this->_request;
}
/**
* Возвращает HTTP код ответа
*
* @return int
*
* Test: @see ResponseTest::testSetupHttpCode()
*
* @tag #response #getter #httpCode
*/
private function getterHttpCode(): int
{
return $this->_httpCode;
}
/**
* Возвращает данные ответа
*
* @return mixed
*
* Test: @see ResponseTest::testSetupData()
*
* @tag #response #getter #data
*/
private function getterData(): mixed
{
if ($this->isArray) {
$content = $this->convertDataToArray($this->_data);
if ($content === null) {
$content = $this->_data;
$this->_errors[] = 'Unknown data type: ' . gettype($content);
}
} else {
$content = $this->_data;
}
return $content;
}
/**
* Преобразует объект или JSON-массив; неподдерживаемый результат оставляет для fallback.
*
* @param mixed $data Исходное содержимое ответа.
*
* @return ?array
*
* Test: @see ResponseTest::testSetupData()
*
* @tag #response #data #array
*/
private function convertDataToArray(mixed $data): ?array
{
$resp = null;
if (is_array($data) || is_object($data)) {
$resp = (array)$data;
} elseif (is_string($data)) {
$resp = json_decode($data, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$resp = null;
$this->_errors[] = 'JSON decode error: ' . json_last_error_msg();
}
}
return is_array($resp) ? $resp : null;
}
}