Completed
Push — master ( 49833f...63cd37 )
by Andrii
14:54
created

Json::formatContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
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 Lcobucci\ContentNegotiation\ContentFormatter;
12
use Throwable;
13
14
final class Json extends ContentFormatter
15
{
16
    private const DEFAULT_FLAGS = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES;
17
18
    /**
19
     * @var int
20
     */
21
    private $flags;
22
23
    public function __construct(int $flags = self::DEFAULT_FLAGS)
24
    {
25
        $this->flags = $flags;
26
    }
27
28
    protected function formatContent($content, array $attributes = []): string
29
    {
30
        if ($content instanceof Throwable) {
31
            return $this->formatException($content);
32
        }
33
34
        return $this->encode($content);
35
    }
36
37
    protected function formatException(Throwable $e): string
38
    {
39
        $message = $e->getMessage();
40
41
        return $this->encode([
42
            '_error' => $message,
43
            '_error_ops' => [
44
                'class' => get_class($e),
45
                // XXX causes Uncaught JsonException: Recursion detected
46
                // TODO fix and return the trace back
47
                //'trace' => $e->getTrace()
48
            ],
49
        ]);
50
    }
51
52
    protected function encode($data): string
53
    {
54
        $res = json_encode($data, $this->flags | JSON_THROW_ON_ERROR);
55
        assert(is_string($res));
56
57
        return $res;
58
    }
59
}
60