JsonRenderer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Conia\Chuck\Renderer;
6
7
use Conia\Chuck\Factory;
8
use Conia\Chuck\Response;
9
use Traversable;
10
11
/** @psalm-api */
12
class JsonRenderer implements Renderer
13
{
14 12
    public function __construct(protected Factory $factory)
15
    {
16 12
    }
17
18 11
    public function render(mixed $data, mixed ...$args): string
19
    {
20 11
        $flags = JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR;
21
22 11
        if (count($args) > 0) {
23
            /** @var mixed */
24 1
            $arg = $args[array_key_first($args)];
25
26 1
            if (is_int($arg)) {
27 1
                $flags = $arg;
28
            }
29
        }
30
31 11
        if ($data instanceof Traversable) {
32 2
            return json_encode(iterator_to_array($data), $flags);
33
        }
34
35 10
        return json_encode($data, $flags);
36
    }
37
38 7
    public function response(mixed $data, mixed ...$args): Response
39
    {
40 7
        $response = Response::fromFactory($this->factory);
41 7
        $response->header('Content-Type', 'application/json');
42 7
        $response->body($this->render($data, ...$args));
43
44 7
        return $response;
45
    }
46
}
47