Failed Conditions
Push — master ( 5f5e96...daf37e )
by Adrien
03:02
created

DbHandler::enable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Log\Handler;
6
7
use Closure;
8
use Ecodev\Felix\Repository\LogRepository;
9
use Monolog\Handler\AbstractProcessingHandler;
10
use Monolog\Level;
11
use Monolog\LogRecord;
12
13
/**
14
 * Will log INFO or more to database, but only if a DB connection has already been connected,
15
 * otherwise all log records are entirely ignored.
16
 *
17
 * `\Application\Model\Log` **MUST** exist and implement `\Ecodev\Felix\Repository\LogRepository`.
18
 */
19
class DbHandler extends AbstractProcessingHandler
20
{
21
    private LogRepository $logRepository;
22
23
    private bool $enabled = false;
24
25 2
    public function __construct(
26
        /**
27
         * @var Closure(): LogRepository
28
         */
29
        private readonly Closure $logRepositoryGetter,
30
    ) {
31 2
        parent::__construct(Level::Info);
32
    }
33
34 2
    public function isHandling(LogRecord $record): bool
35
    {
36 2
        return $this->enabled && parent::isHandling($record);
37
    }
38
39
    /**
40
     * Write a message to the DB.
41
     */
42 1
    protected function write(LogRecord $record): void
43
    {
44 1
        if (!isset($this->logRepository)) {
45 1
            $this->logRepository = $this->logRepositoryGetter->__invoke();
46
        }
47
48 1
        $this->logRepository->log($record);
49
    }
50
51 1
    public function enable(): void
52
    {
53 1
        $this->enabled = true;
54
    }
55
}
56