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

HumanReadableExceptionFormatter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 2
dl 0
loc 36
ccs 0
cts 29
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 8 2
A format() 0 9 2
A printWithoutException() 0 8 1
A printFromException() 0 5 1
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