Json::render()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace alkemann\h2l\response;
4
5
use alkemann\h2l\Message;
6
use alkemann\h2l\Response;
7
use alkemann\h2l\Environment;
8
use alkemann\h2l\util\Http;
9
10
/**
11
 * Class Json
12
 *
13
 * @package alkemann\h2l
14
 */
15
class Json extends Response
16
{
17
    /**
18
     * @param mixed $content JSON encodable payload
19
     * @param int $code HTTP code to respond with, defaults to `200`
20
     * @param array<string, mixed> $config inject config/overrides like `header_func`
21
     */
22
    public function __construct($content = null, int $code = Http::CODE_OK, array $config = [])
23
    {
24
        $this->config = $config + [
25
            'encode_options' => Environment::get('json_encode_options', JSON_THROW_ON_ERROR),
26
            'encode_depth' => Environment::get('json_encode_depth', 512),
27
            'container' => Environment::get('json_encode_container', true),
28
        ];
29
        $this->message = (new Message())
30
            ->withCode($code)
31
            ->withHeaders(['Content-Type' => Http::CONTENT_JSON])
32
            ->withBody($this->encodeAndContainData($content))
33
        ;
34
    }
35
36
    /**
37
     * Set header and return a string rendered and ready to be echo'ed as response
38
     *
39
     * Header 'Content-type:' will be set using `header` or an injeced 'header_func' through constructor
40
     *
41
     * @return string
42
     */
43
    public function render(): string
44
    {
45
        $this->setHeaders();
46
        return $this->message->body();
47
    }
48
49
    /**
50
     * @param mixed $content something that can be Json Enccoded
51
     * @return string
52
     * @throws \JsonException on encode errors
53
     */
54
    private function encodeAndContainData($content): string
55
    {
56
        if (empty($content)) {
57
            return "";
58
        }
59
        if ($content instanceof \Generator) {
60
            $content = iterator_to_array($content);
61
        }
62
        $container = $this->config['container'] ? ['data' => $content] : $content;
63
        $json = json_encode(
64
            $container,
65
            $this->config['encode_options'],
66
            $this->config['encode_depth']
67
        );
68
        return is_string($json) ? $json : '';
0 ignored issues
show
introduced by
The condition is_string($json) is always true.
Loading history...
69
    }
70
}
71