1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Koded package. |
5
|
|
|
* |
6
|
|
|
* (c) Mihail Binev <[email protected]> |
7
|
|
|
* |
8
|
|
|
* Please view the LICENSE distributed with this source code |
9
|
|
|
* for the full copyright and license information. |
10
|
|
|
* |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace Koded\Http; |
14
|
|
|
|
15
|
|
|
use Koded\Http\Interfaces\HttpStatus; |
16
|
|
|
use Koded\Stdlib\Serializer\JsonSerializer; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* HTTP response object for JSON format. |
20
|
|
|
*/ |
21
|
|
|
class JsonResponse extends ServerResponse |
22
|
|
|
{ |
23
|
|
|
public function __construct( |
24
|
|
|
mixed $content = null, |
25
|
|
|
int $statusCode = HttpStatus::OK, |
26
|
|
|
array $headers = []) |
27
|
|
|
{ |
28
|
|
|
parent::__construct( |
29
|
|
|
$this->process($content), |
30
|
|
|
$statusCode, |
31
|
|
|
$headers); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Converts the <, >, ', & and " to UTF-8 variants. |
36
|
|
|
* The content is safe for embedding it into HTML. |
37
|
|
|
* |
38
|
|
|
* @return JsonResponse |
39
|
|
|
*/ |
40
|
|
|
public function safe(): JsonResponse |
41
|
|
|
{ |
42
|
|
|
$this->stream = create_stream(\json_encode( |
43
|
|
|
\json_decode($this->stream->getContents(), true), |
44
|
|
|
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT |
45
|
|
|
)); |
46
|
|
|
return $this; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getContentType(): string |
50
|
|
|
{ |
51
|
|
|
return $this->getHeaderLine('Content-Type') ?: 'application/json'; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function process(mixed $content): mixed |
55
|
|
|
{ |
56
|
|
|
if (\is_array($content)) { |
57
|
|
|
return \json_encode($content, JsonSerializer::OPTIONS); |
58
|
|
|
} |
59
|
|
|
if (\is_iterable($content)) { |
60
|
|
|
return \json_encode(\iterator_to_array($content), JsonSerializer::OPTIONS); |
61
|
|
|
} |
62
|
|
|
return $content; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|