Passed
Pull Request — master (#19)
by
unknown
04:48 queued 01:58
created

PostgresLoggerDecorator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 43
ccs 0
cts 19
cp 0
rs 10
c 0
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A isPostgresSystemQuery() 0 11 6
A log() 0 5 1
A extendContext() 0 11 3
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
    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