Passed
Pull Request — master (#19)
by
unknown
02:43
created

DbLoggerDecorator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 1
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Sentry;
6
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\LoggerTrait;
9
10
final class DbLoggerDecorator implements LoggerInterface
11
{
12
    use LoggerTrait;
13
14
    public const LOG_CATEGORY = 'db_app';
15
    public const ORM_QUERY_LOG_CATEGORY = 'db_sys';
16
17
    public function __construct(
18
        private LoggerInterface $defaultLogger
19
    ) {
20
    }
21
22
    public function log($level, string|\Stringable $message, array $context = []): void
23
    {
24
        $extendedContext = $this->extendContext($context, (string)$message);
25
26
        $this->defaultLogger->log($level, $message, $extendedContext);
27
    }
28
29
    private function extendContext(array $context, string $message): array
30
    {
31
        if ($this->isPostgresSystemQuery($message)) {
32
            $context['category'] = self::ORM_QUERY_LOG_CATEGORY;
33
        } else {
34
            $context['category'] = self::LOG_CATEGORY;
35
        }
36
37
        $context['time'] = empty($context['time']) ? microtime(true) : (float)$context['time'];
38
39
        return $context;
40
    }
41
42
    protected function isPostgresSystemQuery(string $srcQuery): bool
43
    {
44
        $query = strtolower($srcQuery);
45
46
        return
47
            strpos($query, 'tc.constraint_name')
48
            || strpos($query, 'pg_indexes')
49
            || strpos($query, 'tc.constraint_name')
50
            || strpos($query, 'pg_constraint')
51
            || strpos($query, 'information_schema')
52
            || strpos($query, 'pg_class');
53
    }
54
}
55