Passed
Push — master ( 184cb3...5f1713 )
by Waaaaaaaaaa
02:19
created

MonologHandler::write()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 12
nop 1
dl 0
loc 27
ccs 0
cts 16
cp 0
crap 56
rs 8.8333
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Logfile;
4
5
use Monolog\Logger;
6
use Monolog\Handler\AbstractProcessingHandler;
7
use Monolog\Formatter\FormatterInterface;
8
9
class MonologHandler extends AbstractProcessingHandler
10
{
11
    protected $logfile;
12
13
    public function __construct(Logfile $logfile, int $level = Logger::DEBUG, bool $bubble = true)
14
    {
15
        $this->logfile = $logfile;
16
        parent::__construct($level, $bubble);
17
    }
18
19
    protected function getDefaultFormatter(): FormatterInterface
20
    {
21
        return new MonologFormatter();
22
    }
23
24
    protected function write(array $record)
25
    {
26
        $config = clone $this->logfile->getConfig();
27
28
        foreach ($record['context'] as $key => $value) {
29
            if ('exception' === $key && $value instanceof \Throwable) {
30
                continue;
31
            }
32
            $config->addTag($key, $value);
33
        }
34
35
        foreach ($record['extra'] as $key => $value) {
36
            $config->addTag($key, $value);
37
        }
38
39
        $payload = new Payload($record['message'], $config);
40
41
        if (isset($record['context']['exception']) && ($record['context']['exception'] instanceof \Throwable)) {
42
            $payload->pushException($record['context']['exception']);
43
        }
44
45
        $payload->setExtra('level', $record['level']);
46
        $payload->setExtra('level_name', $record['level_name']);
47
        $payload->setExtra('channel', $record['channel']);
48
        $payload->setExtra('datetime', $record['datetime']);
49
50
        $this->logfile->log($payload);
51
    }
52
}
53