Json::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace hiapi\Core\Console\Formatter;
4
5
use const JSON_HEX_AMP;
6
use const JSON_HEX_APOS;
7
use const JSON_HEX_QUOT;
8
use const JSON_HEX_TAG;
9
use const JSON_THROW_ON_ERROR;
10
use const JSON_UNESCAPED_SLASHES;
11
use hiapi\exceptions\SystemError;
12
use Lcobucci\ContentNegotiation\Formatter\ContentOnly;
13
use Throwable;
14
15
final class Json extends ContentOnly
16
{
17
    private const DEFAULT_FLAGS = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES;
18
19
    /**
20
     * @var int
21
     */
22
    private $flags;
23
24
    public function __construct(int $flags = self::DEFAULT_FLAGS)
25
    {
26
        $this->flags = $flags;
27
    }
28
29
    public function formatContent($content, array $attributes = []): string
30
    {
31
        if ($content instanceof Throwable) {
32
            return $this->formatException($content);
33
        }
34
35
        return $this->encode($content);
36
    }
37
38
    protected function formatException(Throwable $e): string
39
    {
40
        $system = $e instanceof SystemError;
41
        $source = $system ? $e->getPrevious() ?? $e : $e;
42
43
        return $this->encode([
44
            '_error' => $e->getMessage(),
45
            '_error_ops' => array_filter([
46
                'at' => Json::class,
47
                'class' => get_class($source),
48
                'data' =>  $system ? $e->getData() : null,
49
                'message' => getenv('ENV') === 'prod' ? '' : $source->getMessage(),
50
            ]),
51
        ]);
52
    }
53
54
    protected function encode($data): string
55
    {
56
        $res = json_encode($data, $this->flags | JSON_THROW_ON_ERROR);
57
        assert(is_string($res));
58
59
        return $res;
60
    }
61
}
62