Passed
Push — master ( 3eb4db...99d5ff )
by Kirill
03:12
created

JsonHandler::renderTrace()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 27
rs 9.3888
cc 5
nc 5
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Exceptions;
13
14
final class JsonHandler extends AbstractHandler
15
{
16
    /**
17
     * @param \Throwable $e
18
     * @param int        $verbosity
19
     * @return string
20
     */
21
    public function renderException(\Throwable $e, int $verbosity = self::VERBOSITY_VERBOSE): string
22
    {
23
        return json_encode([
24
            'error'      => sprintf(
25
                '[%s] %s as %s:%s',
26
                get_class($e),
27
                $e->getMessage(),
28
                $e->getFile(),
29
                $e->getLine()
30
            ),
31
            'stacktrace' => iterator_to_array($this->renderTrace($e->getTrace(), $verbosity))
32
        ]);
33
    }
34
35
    /**
36
     * @param array $trace
37
     * @param int   $verbosity
38
     * @return \Generator
39
     */
40
    private function renderTrace(array $trace, int $verbosity): \Generator
41
    {
42
        foreach ($trace as $item) {
43
            $result = [];
44
45
            if (isset($item['class'])) {
46
                $result['function'] = sprintf(
47
                    '%s%s%s()',
48
                    $item['class'],
49
                    $item['type'],
50
                    $item['function']
51
                );
52
            } else {
53
                $result['function'] = sprintf(
54
                    '%s()',
55
                    $item['function']
56
                );
57
            }
58
59
            if ($verbosity >= self::VERBOSITY_VERBOSE && isset($item['file'])) {
60
                $result['at'] = [
61
                    'file' => $item['file'] ?? null,
62
                    'line' => $item['line'] ?? null
63
                ];
64
            }
65
66
            yield$result;
67
        }
68
    }
69
}
70