Newer
Older
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
<?php
namespace App\Response;
use ReflectionClass;
use Symfony\Component\HttpFoundation\JsonResponse;
class ApiResponse extends JsonResponse
{
private bool $status = true;
private array $messages = [];
private ?array $responseData = null;
public function __construct(mixed $data = null, int $status = 200, array $headers = [], bool $json = false)
{
parent::__construct($data, $status, $headers, $json);
$this->setResult();
}
/**
* Добавление ошибки
*
* @param string $message
*
* @return self
*/
public function addError(string $message): self
{
$this->status = false;
return $this->addMessage($message);
}
/**
* Добавление ошибок
*
* @param array $errors
*
* @return $this
*/
public function addErrors(array $errors): self
{
$this->status = false;
foreach ($errors as $error) {
$this->addError($error);
}
return $this;
}
/**
* Добавление сообщения
*
* @param string $message
*
* @return self
*/
public function addMessage(string $message): self
{
$this->messages[] = $message;
return $this->setResult();
}
/**
* Запись контента ответа
*
* @param array|null $responseData
*
* @return void
*/
public function setResponseData(?array $responseData): void
{
$this->responseData = $responseData;
$this->setResult();
}
/**
* @return bool
*/
public function isSuccess(): bool
{
return $this->status;
}
/**
* Установка результата
*
* @return self
*/
protected function setResult(): self
{
$result = [
'status' => $this->status,
];
if (!empty($this->responseData)) {
$result['data'] = $this->responseData;
}
if (!isset($result['data'])) {
$result['message'] = implode(', ', $this->messages);
}
return $this->setData($result);
}
}