FlareHandler::write()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 1
dl 0
loc 26
rs 9.1928
c 0
b 0
f 0
1
<?php
2
3
namespace Facade\Ignition\Logger;
4
5
use Facade\FlareClient\Flare;
6
use Facade\Ignition\Ignition;
7
use Facade\Ignition\Tabs\Tab;
8
use Monolog\Handler\AbstractProcessingHandler;
9
use Monolog\Logger;
10
use Throwable;
11
12
class FlareHandler extends AbstractProcessingHandler
13
{
14
    /** @var \Facade\FlareClient\Flare */
15
    protected $flare;
16
17
    protected $minimumReportLogLevel = Logger::ERROR;
18
19
    public function __construct(Flare $flare, $level = Logger::DEBUG, $bubble = true)
20
    {
21
        $this->flare = $flare;
22
23
        parent::__construct($level, $bubble);
24
    }
25
26
    public function setMinimumReportLogLevel(int $level)
27
    {
28
        if (! in_array($level, Logger::getLevels())) {
29
            throw new \InvalidArgumentException('The given minimum log level is not supported.');
30
        }
31
32
        $this->minimumReportLogLevel = $level;
33
    }
34
35
    protected function write(array $report): void
36
    {
37
        if (! $this->shouldReport($report)) {
38
            return;
39
        }
40
41
        if ($this->hasException($report)) {
42
            /** @var Throwable $throwable */
43
            $throwable = $report['context']['exception'];
44
45
            collect(Ignition::$tabs)
46
                ->each(function (Tab $tab) use ($throwable) {
47
                    $tab->beforeRenderingErrorPage($this->flare, $throwable);
48
                });
49
50
            $this->flare->report($report['context']['exception']);
51
52
            return;
53
        }
54
55
        if (config('flare.send_logs_as_events')) {
56
            if ($this->hasValidLogLevel($report)) {
57
                $this->flare->reportMessage($report['message'], 'Log '.Logger::getLevelName($report['level']));
58
            }
59
        }
60
    }
61
62
    protected function shouldReport(array $report): bool
63
    {
64
        return $this->hasException($report) || $this->hasValidLogLevel($report);
65
    }
66
67
    protected function hasException(array $report): bool
68
    {
69
        $context = $report['context'];
70
71
        return isset($context['exception']) && $context['exception'] instanceof Throwable;
72
    }
73
74
    protected function hasValidLogLevel(array $report): bool
75
    {
76
        return $report['level'] >= $this->minimumReportLogLevel;
77
    }
78
}
79