Completed
Push — master ( 9a342a...a162ae )
by Andrii
13:06
created

Json::formatException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace hiapi\Core\Console\Formatter;
4
5
use Lcobucci\ContentNegotiation\Formatter;
6
use Throwable;
7
use const JSON_HEX_AMP;
8
use const JSON_HEX_APOS;
9
use const JSON_HEX_QUOT;
10
use const JSON_HEX_TAG;
11
use const JSON_THROW_ON_ERROR;
12
use const JSON_UNESCAPED_SLASHES;
13
14
final class Json implements Formatter
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
    /**
29
     * {@inheritdoc}
30
     */
31
    public function format($content, array $attributes = []): string
32
    {
33
        if ($content instanceof Throwable) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
34
            return $this->formatException($content);
35
        }
36
37
        return $this->encode($content);
38
    }
39
40
    protected function formatException(Throwable $e): string
41
    {
42
        $message = $e->getMessage();
43
44
        return $this->encode([
45
            '_error' => $message,
46
            '_error_ops' => [
47
                'class' => get_class($e),
48
                'trace' => $e->getTrace()
49
            ],
50
        ]);
51
    }
52
53
    protected function encode($data): string
54
    {
55
        $res = json_encode($data, $this->flags | JSON_THROW_ON_ERROR);
56
        assert(is_string($res));
57
58
        return $res;
59
    }
60
}
61