Json.php
5 months ago
JsonColumnFactory.php
5 months ago
JsonListScreenSettingsFactory.php
5 months ago
Json.php
104 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Response; |
| 6 | |
| 7 | use LogicException; |
| 8 | |
| 9 | class Json |
| 10 | { |
| 11 | |
| 12 | public const MESSAGE = 'message'; |
| 13 | |
| 14 | protected array $parameters = []; |
| 15 | |
| 16 | protected array $headers = []; |
| 17 | |
| 18 | protected int $status_code = 200; |
| 19 | |
| 20 | public function __construct(array $parameters = []) |
| 21 | { |
| 22 | $this->set_header('Content-Type', 'application/json'); |
| 23 | |
| 24 | $this->parameters = $parameters; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * @return never |
| 29 | */ |
| 30 | public function send(): void |
| 31 | { |
| 32 | if (empty($this->parameters)) { |
| 33 | throw new LogicException('Missing response body.'); |
| 34 | } |
| 35 | |
| 36 | $this->send_response($this->parameters); |
| 37 | } |
| 38 | |
| 39 | private function send_response($data): void |
| 40 | { |
| 41 | status_header($this->status_code); |
| 42 | |
| 43 | foreach ($this->headers as $header) { |
| 44 | header($header); |
| 45 | } |
| 46 | |
| 47 | echo json_encode($data); |
| 48 | exit; |
| 49 | } |
| 50 | |
| 51 | public function error(): void |
| 52 | { |
| 53 | $this->send_response([ |
| 54 | 'success' => false, |
| 55 | 'data' => $this->parameters, |
| 56 | ]); |
| 57 | } |
| 58 | |
| 59 | public function success(): void |
| 60 | { |
| 61 | $this->send_response([ |
| 62 | 'success' => true, |
| 63 | 'data' => $this->parameters, |
| 64 | ]); |
| 65 | } |
| 66 | |
| 67 | public function set_parameter($key, $value): self |
| 68 | { |
| 69 | $this->parameters[$key] = $value; |
| 70 | |
| 71 | return $this; |
| 72 | } |
| 73 | |
| 74 | public function set_parameters(array $values): self |
| 75 | { |
| 76 | foreach ($values as $key => $value) { |
| 77 | $this->set_parameter($key, $value); |
| 78 | } |
| 79 | |
| 80 | return $this; |
| 81 | } |
| 82 | |
| 83 | public function set_header(string $name, string $value): self |
| 84 | { |
| 85 | $this->headers[] = sprintf('%s: %s', $name, $value); |
| 86 | |
| 87 | return $this; |
| 88 | } |
| 89 | |
| 90 | public function set_message(string $message): self |
| 91 | { |
| 92 | $this->set_parameter(self::MESSAGE, $message); |
| 93 | |
| 94 | return $this; |
| 95 | } |
| 96 | |
| 97 | public function set_status_code(int $code): self |
| 98 | { |
| 99 | $this->status_code = $code; |
| 100 | |
| 101 | return $this; |
| 102 | } |
| 103 | |
| 104 | } |