1: | <?php |
2: | |
3: | namespace ngatngay\http; |
4: | |
5: | class response { |
6: | private mixed $data; |
7: | private int $status; |
8: | private array $headers = []; |
9: | private static bool $is_sended = false; |
10: | |
11: | public function __construct( |
12: | mixed $data = null, |
13: | int $status = 200, |
14: | array $headers = [] |
15: | ) { |
16: | $this->data = $data; |
17: | $this->status = $status; |
18: | $this->headers = $headers; |
19: | } |
20: | |
21: | public function data(mixed $data): self |
22: | { |
23: | $this->data = $data; |
24: | return $this; |
25: | } |
26: | public function status(int $status): self |
27: | { |
28: | $this->status = $status; |
29: | return $this; |
30: | } |
31: | public function json(): self |
32: | { |
33: | $this->headers += ['Content-Type: application/json']; |
34: | |
35: | if (is_array($this->data)) { |
36: | $this->data = json_encode($this->data); |
37: | } |
38: | return $this; |
39: | } |
40: | |
41: | public function headers(array $headers): self |
42: | { |
43: | $this->headers = $headers; |
44: | return $this; |
45: | } |
46: | |
47: | public function send(): void |
48: | { |
49: | static $is_sended; |
50: | |
51: | if ($is_sended) { |
52: | return; |
53: | } else { |
54: | $is_sended = true; |
55: | } |
56: | |
57: | if (is_array($this->data)) { |
58: | $this->json(); |
59: | } |
60: | |
61: | http_response_code($this->status); |
62: | |
63: | $this->headers = array_unique($this->headers); |
64: | foreach ($this->headers as $header) { |
65: | header($header); |
66: | } |
67: | |
68: | echo $this->data; |
69: | |
70: | if (\function_exists('fastcgi_finish_request')) { |
71: | fastcgi_finish_request(); |
72: | } elseif (\function_exists('litespeed_finish_request')) { |
73: | litespeed_finish_request(); |
74: | } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) { |
75: | static::close_output_buffers(0, true); |
76: | flush(); |
77: | } |
78: | } |
79: | |
80: | public static function close_output_buffers(int $targetLevel, bool $flush): void |
81: | { |
82: | $status = ob_get_status(true); |
83: | $level = \count($status); |
84: | $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE); |
85: | |
86: | while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) { |
87: | if ($flush) { |
88: | ob_end_flush(); |
89: | } else { |
90: | ob_end_clean(); |
91: | } |
92: | } |
93: | } |
94: | } |