1: <?php
2:
3: namespace ngatngay\http;
4:
5: class response
6: {
7: private $data;
8: /**
9: * @var int
10: */
11: private $status;
12: /**
13: * @var array
14: */
15: private $headers = [];
16: /**
17: * @var bool
18: */
19: private static $is_sended = false;
20:
21: /**
22: * @param mixed $data
23: * @param int $status
24: * @param array $headers
25: */
26: public function __construct(
27: $data = null,
28: $status = 200,
29: $headers = []
30: ) {
31: $this->data = $data;
32: $this->status = $status;
33: $this->headers = $headers;
34: }
35:
36: /**
37: * @param mixed $data
38: * @return self
39: */
40: public function data($data)
41: {
42: $this->data = $data;
43: return $this;
44: }
45: /**
46: * @param int $status
47: * @return self
48: */
49: public function status($status)
50: {
51: $this->status = $status;
52: return $this;
53: }
54:
55: /**
56: * @param bool $prettify
57: * @return self
58: */
59: public function json($prettify = false)
60: {
61: $this->headers += ['Content-Type: application/json'];
62:
63: if (is_array($this->data) || is_object($this->data)) {
64: $flags = 0;
65:
66: $flags |= JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
67:
68: if ($prettify) {
69: $flags |= JSON_PRETTY_PRINT;
70: }
71:
72: $this->data = json_encode($this->data, $flags);
73: }
74:
75: return $this;
76: }
77:
78: /**
79: * @param array $headers
80: * @return self
81: */
82: public function headers($headers)
83: {
84: $this->headers = $headers;
85: return $this;
86: }
87:
88: /**
89: * @return void
90: */
91: public function send()
92: {
93: static $is_sended;
94:
95: if ($is_sended) {
96: return;
97: } else {
98: $is_sended = true;
99: }
100:
101: if (is_array($this->data)) {
102: $this->json();
103: }
104:
105: http_response_code($this->status);
106:
107: $this->headers = array_unique($this->headers);
108: foreach ($this->headers as $header) {
109: header($header);
110: }
111:
112: echo $this->data;
113:
114: if (\function_exists('fastcgi_finish_request')) {
115: fastcgi_finish_request();
116: } elseif (\function_exists('litespeed_finish_request')) {
117: litespeed_finish_request();
118: } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
119: static::close_output_buffers(0, true);
120: flush();
121: }
122: }
123:
124: /**
125: * @param int $targetLevel
126: * @param bool $flush
127: * @return void
128: */
129: public static function close_output_buffers($targetLevel, $flush)
130: {
131: $status = ob_get_status(true);
132: $level = \count($status);
133: $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE);
134:
135: while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
136: if ($flush) {
137: ob_end_flush();
138: } else {
139: ob_end_clean();
140: }
141: }
142: }
143: }
144: