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

PostgresLoggerDecorator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 41
ccs 0
cts 19
cp 0
rs 10
c 2
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 1 1
A log() 0 5 1
A extendContext() 0 11 3
A isSystemQuery() 0 11 6
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
    public function log($level, string|\Stringable $message, array $context = []): void
21
    {
22
        $extendedContext = $this->extendContext($context, (string)$message);
23
24
        $this->defaultLogger->log($level, $message, $extendedContext);
25
    }
26
27
    private function extendContext(array $context, string $message): array
28
    {
29
        if ($this->isSystemQuery($message)) {
30
            $context['category'] = self::ORM_QUERY_LOG_CATEGORY;
31
        } else {
32
            $context['category'] = self::LOG_CATEGORY;
33
        }
34
35
        $context['time'] = empty($context['time']) ? microtime(true) : (float)$context['time'];
36
37
        return $context;
38
    }
39
40
    protected function isSystemQuery(string $srcQuery): bool
41
    {
42
        $query = strtolower($srcQuery);
43
44
        return (
45
            str_contains($query, 'tc.constraint_name') ||
46
            str_contains($query, 'pg_indexes') ||
47
            str_contains($query, 'tc.constraint_name') ||
48
            str_contains($query, 'pg_constraint') ||
49
            str_contains($query, 'information_schema') ||
50
            str_contains($query, 'pg_class')
51
        );
52
    }
53
}
54