Completed
Pull Request — master (#6)
by Walter
09:44
created

printFromThrowable()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 0
cts 20
cp 0
rs 8.9713
c 0
b 0
f 0
cc 1
eloc 17
nc 1
nop 2
crap 2
1
<?php
2
3
namespace PolderKnowledge\LogModule\Formatter;
4
5
use Monolog\Formatter\LineFormatter;
6
use WShafer\PSR11MonoLog\FactoryInterface;
7
8
/**
9
 * Format an Exception in a similar way PHP does by default when an exception bubbles to the top
10
 */
11
class HumanReadableExceptionFormatter extends LineFormatter implements FactoryInterface
12
{
13
    public function __invoke(array $options)
14
    {
15
        if (array_key_exists('dateFormat', $options)) {
16
            return new self($options['dateFormat']);
17
        }
18
19
        return new self();
20
    }
21
22
    public function format(array $record): string
23
    {
24
        $exception = $record['context']['exception'] ?? null;
25
26
        if (!$exception) {
27
            return parent::format($record);
28
        }
29
30
        return $this->printFromThrowable($record, $exception);
31
    }
32
33
    protected function printFromThrowable(array $record, \Throwable $throwable)
34
    {
35
        $record = $this->normalize($record);
36
37
        $result = sprintf(
38
            "[%s] %s.%s: %s\n\n",
39
            $record['datetime'],
40
            $record['channel'],
41
            $record['level_name'],
42
            $record['message']
43
        );
44
45
        $result .= "[Context]\n";
46
        $result .= sprintf("  Type: %s\n", get_class($throwable));
47
        $result .= sprintf("  Code: %d\n", $throwable->getCode());
48
        $result .= sprintf("  File: %s\n", $throwable->getFile());
49
        $result .= sprintf("  Line: %d\n\n", $throwable->getLine());
50
51
        $result .= "[Trace]\n";
52
        $result .= $this->buildTraceOutput($throwable->getTraceAsString());
53
        $result .= "\n\n";
54
55
        return $result;
56
    }
57
58
    private function buildTraceOutput($trace)
59
    {
60
        $lines = explode("\n", $trace);
61
62
        $indented = array_map(function ($item) {
63
            return '  ' . $item;
64
        }, $lines);
65
66
        return implode("\n", $indented);
67
    }
68
}
69