DoctrineDbalLogger::escapeParams()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 20
ccs 11
cts 11
cp 1
rs 9.6111
cc 5
nc 5
nop 1
crap 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