Passed
Push — master ( 7f192b...2c59bc )
by Mihail
13:03 queued 41s
created

JsonResponse::safe()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 4
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 7
rs 10
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,
25
        int $statusCode = HttpStatus::OK,
26
        array $headers = [])
27
    {
28
        parent::__construct($this->process($content), $statusCode, $headers);
29
    }
30
31
    /**
32
     * Converts the <, >, ', & and " to UTF-8 variants.
33
     * The content is safe for embedding it into HTML.
34
     *
35
     * @return JsonResponse
36
     */
37
    public function safe(): JsonResponse
38
    {
39
        $this->stream = create_stream(\json_encode(
40
            \json_decode($this->stream->getContents(), true),
41
            JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
42
        ));
43
        return $this;
44
    }
45
46
    public function getContentType(): string
47
    {
48
        return $this->getHeaderLine('Content-Type') ?: 'application/json';
49
    }
50
51
    private function process(mixed $content): mixed
52
    {
53
        if (\is_array($content)) {
54
            return \json_encode($content, JsonSerializer::OPTIONS);
55
        }
56
        if (\is_iterable($content)) {
57
            return \json_encode(\iterator_to_array($content), JsonSerializer::OPTIONS);
58
        }
59
        return $content;
60
    }
61
}
62