|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Source\Core; |
|
4
|
|
|
|
|
5
|
|
|
final class Response |
|
6
|
|
|
{ |
|
7
|
|
|
private $headers = [ |
|
8
|
|
|
'Content-Type' => 'application/json', |
|
9
|
|
|
'Cache-Control' => 'no-cache', |
|
10
|
|
|
'Pragma' => 'no-cache', |
|
11
|
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, OPTIONS, DELETE', |
|
12
|
|
|
'Accept-Language' => 'en-US;q=0.5,en;q=0.3', |
|
13
|
|
|
'Keep-Alive' => 'timeout=5, max=100', |
|
14
|
|
|
'Connection' => 'keep-alive' |
|
15
|
|
|
]; |
|
16
|
|
|
|
|
17
|
|
|
private const HTTP_PROTOCOL = 'HTTP/1.1'; |
|
18
|
|
|
|
|
19
|
|
|
private $statusCode; |
|
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
private $message; |
|
22
|
|
|
|
|
23
|
|
|
public function __construct($customHeaders = null) |
|
24
|
|
|
{ |
|
25
|
|
|
if (!empty($customHeaders)) { |
|
26
|
|
|
$this->addHeader($customHeaders); |
|
27
|
|
|
} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
private function addHeader(array $headers): void |
|
31
|
|
|
{ |
|
32
|
|
|
foreach ($headers as $key => $value) { |
|
33
|
|
|
$this->headers[$key] = $value; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
return; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
private function setHeaders(): void |
|
40
|
|
|
{ |
|
41
|
|
|
foreach ($this->headers as $key => $value) { |
|
42
|
|
|
header("{$key}: {$value}"); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
private function setMessage(object $message): Response |
|
49
|
|
|
{ |
|
50
|
|
|
if (!is_array((array) $message)) { |
|
|
|
|
|
|
51
|
|
|
throw new \Exception("Invalid message"); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
$this->message = $message; |
|
55
|
|
|
|
|
56
|
|
|
return $this; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public function setStatusCode(int $statusCode): Response |
|
60
|
|
|
{ |
|
61
|
|
|
$text = $this->handleCode($statusCode); |
|
62
|
|
|
|
|
63
|
|
|
header(self::HTTP_PROTOCOL . " {$statusCode} {$text}"); |
|
64
|
|
|
|
|
65
|
|
|
return $this; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
private function handleCode(int $statusCode): string |
|
69
|
|
|
{ |
|
70
|
|
|
if (($text = handleStatusCode($statusCode)) == 'unknown') { |
|
71
|
|
|
throw new \Exception("Unknown status code"); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return $text; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
public function send(object $message): void |
|
78
|
|
|
{ |
|
79
|
|
|
$this->setMessage($message); |
|
80
|
|
|
$this->setHeaders(); |
|
81
|
|
|
$this->sendResponse(); |
|
82
|
|
|
|
|
83
|
|
|
exit; |
|
|
|
|
|
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
private function sendResponse(): void |
|
87
|
|
|
{ |
|
88
|
|
|
echo json_encode((array) $this->message); |
|
89
|
|
|
|
|
90
|
|
|
return; |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|