Passed
Pull Request — master (#17)
by Mihail
15:10
created

JsonResponse   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 14
c 2
b 0
f 1
dl 0
loc 42
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getContentType() 0 3 2
A preparePayload() 0 9 3
A __construct() 0 9 1
A safe() 0 7 1
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
use function is_array;
18
use function is_iterable;
19
use function iterator_to_array;
20
use function json_decode;
21
use function json_encode;
22
23
/**
24
 * HTTP response object for JSON format.
25
 */
26
class JsonResponse extends ServerResponse
27
{
28
    public function __construct(
29
        mixed $content = '',
30
        int $statusCode = HttpStatus::OK,
31
        array $headers = [])
32
    {
33
        parent::__construct(
34
            $this->preparePayload($content),
35
            $statusCode,
36
            $headers);
37
    }
38
39
    /**
40
     * Converts the <, >, ', & and " to UTF-8 variants.
41
     * The content is safe for embedding it into HTML.
42
     *
43
     * @return JsonResponse
44
     */
45
    public function safe(): static
46
    {
47
        $this->stream = create_stream(json_encode(
48
            json_decode($this->stream->getContents(), true),
49
            JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
50
        ));
51
        return $this;
52
    }
53
54
    public function getContentType(): string
55
    {
56
        return $this->getHeaderLine('Content-Type') ?: 'application/json';
57
    }
58
59
    private function preparePayload(mixed $content): mixed
60
    {
61
        if (is_array($content)) {
62
            return json_encode($content, JsonSerializer::OPTIONS);
63
        }
64
        if (is_iterable($content)) {
65
            return json_encode(iterator_to_array($content), JsonSerializer::OPTIONS);
66
        }
67
        return $content;
68
    }
69
}
70