DoctrineDbalLogger   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 19
c 1
b 0
f 0
dl 0
loc 53
ccs 22
cts 22
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A startQuery() 0 8 4
A __construct() 0 3 1
A stopQuery() 0 2 1
A escapeParams() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\DoctrineDbServiceProvider\Logger;
6
7
use Doctrine\DBAL\Logging\SQLLogger;
8
use Psr\Log\LoggerInterface;
9
10
/**
11
 * @see https://github.com/symfony/doctrine-bridge/blob/master/Logger/DbalLogger.php
12
 */
13
final class DoctrineDbalLogger implements SQLLogger
14
{
15
    const MAX_STRING_LENGTH = 32;
16
    const BINARY_DATA_VALUE = '(binary value)';
17
18
    /**
19
     * @var LoggerInterface
20
     */
21
    private $logger;
22
23 2
    public function __construct(LoggerInterface $logger)
24
    {
25 2
        $this->logger = $logger;
26 2
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31 1
    public function startQuery($sql, ?array $params = null, ?array $types = null): void
32
    {
33 1
        if (is_array($params)) {
34 1
            $params = $this->escapeParams($params);
35
        }
36
37 1
        if (null !== $this->logger) {
38 1
            $this->logger->debug($sql, null === $params ? [] : $params);
39
        }
40 1
    }
41
42 1
    public function stopQuery(): void
43
    {
44 1
    }
45
46 1
    private function escapeParams(array $params): array
47
    {
48 1
        foreach ($params as $index => $param) {
49 1
            if (!is_string($param)) {
50 1
                continue;
51
            }
52
53
            // non utf-8 strings break json encoding
54 1
            if (!preg_match('//u', $param)) {
55 1
                $params[$index] = self::BINARY_DATA_VALUE;
56 1
                continue;
57
            }
58
59 1
            if (self::MAX_STRING_LENGTH < mb_strlen($param, 'UTF-8')) {
60 1
                $params[$index] = mb_substr($param, 0, self::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]';
61 1
                continue;
62
            }
63
        }
64
65 1
        return $params;
66
    }
67
}
68