Completed
Push — master ( 83e357...f961ff )
by Nikola
03:07
created

LogHandler::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of the Phoundation package.
4
 *
5
 * Copyright (c) Nikola Posa
6
 *
7
 * For full copyright and license information, please refer to the LICENSE file,
8
 * located at the package root folder.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Phoundation\ErrorHandling\Handler;
14
15
use Psr\Log\LoggerInterface;
16
use Throwable;
17
use Phoundation\Exception\DontLogInterface;
18
use Psr\Log\LogLevel;
19
20
/**
21
 * @author Nikola Posa <[email protected]>
22
 */
23
final class LogHandler
24
{
25
    /**
26
     * @var LoggerInterface
27
     */
28
    private $logger;
29
30
    /**
31
     * @var array
32
     */
33
    private $dontLog;
34
35 8
    public function __construct(LoggerInterface $logger, array $dontLog = [])
36
    {
37 8
        $this->logger = $logger;
38 8
        $this->dontLog = array_merge($dontLog, [DontLogInterface::class]);
39 8
    }
40
41 8
    public function __invoke(Throwable $e)
42
    {
43 8
        if (!$this->shouldLog($e)) {
44 1
            return;
45
        }
46
47 7
        $logLevel = $this->resolveLogLevel($e);
48 7
        $message = $e->getMessage();
49
        $context = [
50 7
            'exception' => $e,
51
        ];
52
53 7
        $this->logger->log($logLevel, $message, $context);
54 7
    }
55
56 8
    private function shouldLog(Throwable $e) : bool
57
    {
58 8
        foreach ($this->dontLog as $type) {
59 8
            if ($e instanceof $type) {
60 8
                return false;
61
            }
62
        }
63
64 7
        return true;
65
    }
66
67 7
    private function resolveLogLevel(Throwable $e)
68
    {
69 7
        if ($e instanceof \ErrorException) {
70 4
            switch ($e->getSeverity()) {
71 4
                case E_ERROR:
72 4
                case E_RECOVERABLE_ERROR:
73 4
                case E_CORE_ERROR:
74 3
                case E_COMPILE_ERROR:
75 3
                case E_USER_ERROR:
76 3
                case E_PARSE:
77 1
                    return LogLevel::ERROR;
78 3
                case E_WARNING:
79 3
                case E_USER_WARNING:
80 2
                case E_CORE_WARNING:
81 2
                case E_COMPILE_WARNING:
82 1
                    return LogLevel::WARNING;
83 2
                case E_NOTICE:
84 1
                case E_USER_NOTICE:
85 1
                case E_STRICT:
86 1
                case E_DEPRECATED:
87
                case E_USER_DEPRECATED:
88 2
                    return LogLevel::NOTICE;
89
                default:
90
                    break;
91
            }
92
        }
93
94 3
        return LogLevel::ERROR;
95
    }
96
}
97