Passed
Push — refactor ( ba928a...de29b8 )
by Akihito
02:37
created

ErrorLogger::log()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
ccs 1
cts 1
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Provide\Error;
6
7
use BEAR\AppMeta\AbstractAppMeta;
8
use BEAR\Sunday\Extension\Router\RouterMatch;
9
use Psr\Log\LoggerInterface;
10
use Throwable;
11
12
use function sprintf;
13
14
final class ErrorLogger
15
{
16
    public function __construct(
17
        private LoggerInterface $logger,
18
        private AbstractAppMeta $appMeta,
19
    ) {
20
    }
21
22
    public function __invoke(Throwable $e, RouterMatch $request): string
23
    {
24
        $isError = $e->getCode() >= 500;
25
        $logRef = new LogRef($e);
26 9
        $logRef->log($e, $request, $this->appMeta);
27
        $message = sprintf('req:"%s" code:%s e:%s(%s) logref:%s', (string) $request, $e->getCode(), $e::class, $e->getMessage(), (string) $logRef);
28 9
        $this->log($isError, $message);
29 9
30 9
        return (string) $logRef;
31
    }
32 1
33
    /**
34 1
     * Log with method
35 1
     *
36 1
     * monolog has different log level constants(200,400) than psr/logger,
37 1
     * and those constants change from version to version.
38 1
     */
39
    private function log(bool $isError, string $message): void
40 1
    {
41
        if ($isError) {
42
            $this->logger->error($message);
43
44
            return;
45
        }
46
47
        $this->logger->debug($message);
48
    }
49
}
50