JsonRenderer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 13
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 18 4
A response() 0 7 1
A __construct() 0 2 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