Completed
Push — master ( 8dce14...ef59ee )
by Freek
13:50
created

FlareHandler   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 65
rs 10
c 0
b 0
f 0
wmc 12
lcom 1
cbo 6

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A setMinimumReportLogLevel() 0 8 2
A write() 0 24 4
A shouldReport() 0 4 2
A hasException() 0 6 2
A hasValidLogLevel() 0 4 1
1
<?php
2
3
namespace Facade\Ignition\Logger;
4
5
use Throwable;
6
use Monolog\Logger;
7
use Facade\FlareClient\Flare;
8
use Facade\Ignition\Ignition;
9
use Facade\Ignition\Tabs\Tab;
10
use Monolog\Handler\AbstractProcessingHandler;
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 ($this->hasValidLogLevel($report)) {
56
            $this->flare->reportMessage($report['message'], 'Log '.Logger::getLevelName($report['level']));
57
        }
58
    }
59
60
    protected function shouldReport(array $report): bool
61
    {
62
        return $this->hasException($report) || $this->hasValidLogLevel($report);
63
    }
64
65
    protected function hasException(array $report): bool
66
    {
67
        $context = $report['context'];
68
69
        return isset($context['exception']) && $context['exception'] instanceof Throwable;
70
    }
71
72
    protected function hasValidLogLevel(array $report): bool
73
    {
74
        return $report['level'] >= $this->minimumReportLogLevel;
75
    }
76
}
77