Test Setup Failed
Push — master ( 781818...decea1 )
by Dominik
07:28
created

DoctrineDbalLogger   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 0
cbo 1
dl 0
loc 55
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A startQuery() 0 10 4
A stopQuery() 0 3 1
A escapeParams() 0 21 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
    public function __construct(LoggerInterface $logger)
24
    {
25
        $this->logger = $logger;
26 2
    }
27
28 2
    /**
29 2
     * {@inheritdoc}
30
     */
31
    public function startQuery($sql, ?array $params = null, ?array $types = null): void
32
    {
33
        if (is_array($params)) {
34 1
            $params = $this->escapeParams($params);
35
        }
36 1
37 1
        if (null !== $this->logger) {
38 1
            $this->logger->debug($sql, null === $params ? [] : $params);
39 1
        }
40
    }
41
42
    public function stopQuery(): void
43 1
    {
44 1
    }
45 1
46
    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
            if (!preg_match('//u', $param)) {
55 1
                $params[$index] = self::BINARY_DATA_VALUE;
56 1
                continue;
57
            }
58 1
59
            if (self::MAX_STRING_LENGTH < mb_strlen($param, 'UTF-8')) {
60
                $params[$index] = mb_substr($param, 0, self::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]';
61
                continue;
62
            }
63 1
        }
64
65 1
        return $params;
66
    }
67
}
68