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

PostgresLoggerDecorator::isSystemQuery()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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