Completed
Push — master ( 00ebf8...088a04 )
by Walter
05:10 queued 01:59
created

HumanReadableExceptionFormatter::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 6
1
<?php
2
3
namespace PolderKnowledge\LogModule\Formatter;
4
5
use Monolog\Formatter\FormatterInterface;
6
use Monolog\Formatter\NormalizerFormatter;
7
use WShafer\PSR11MonoLog\FactoryInterface;
8
9
/**
10
 * Format an Exception in a similar way PHP does by default when an exception bubbles to the top
11
 */
12
class HumanReadableExceptionFormatter extends NormalizerFormatter implements FormatterInterface, FactoryInterface
13
{
14
    public function __invoke(array $options)
15
    {
16
        if (array_key_exists('dateFormat', $options)) {
17
            return new self($options['dateFormat']);
18
        }
19
20
        return new self();
21
    }
22
23
    public function format(array $record): string
24
    {
25
        $exception = $record['context']['exception'] ?? null;
26
        if ($exception) {
27
            return $this->printFromException($exception);
28
        } else {
29
            return $this->printWithoutException($record);
30
        }
31
    }
32
33
    protected function printWithoutException(array $record): string
34
    {
35
        return sprintf("[%s] %s: %s\n", ...[
36
            date('r'),
37
            $record['level_name'],
38
            $record['message']
39
        ]);
40
    }
41
    
42
    protected function printFromException(\Throwable $exception)
43
    {
44
        return implode("\n", ExceptionPrinter::linesFromException($exception)) . "\n"
45
            . "---------------------------------------\n";
46
    }
47
}
48