Completed
Push — master ( ea2079...de4fd9 )
by Dominik
05:49
created

DoctrineDbalLogger::log()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Fabien Potencier <[email protected]> (https://github.com/silexphp/Silex-Providers)
7
 */
8
9
namespace Chubbyphp\ServiceProvider\Logger;
10
11
use Psr\Log\LoggerInterface;
12
use Doctrine\DBAL\Logging\SQLLogger;
13
14
final class DoctrineDbalLogger implements SQLLogger
15
{
16
    const MAX_STRING_LENGTH = 32;
17
    const BINARY_DATA_VALUE = '(binary value)';
18
19
    /**
20
     * @var LoggerInterface
21
     */
22
    private $logger;
23
24
    /**
25
     * @param LoggerInterface $logger
26
     */
27 2
    public function __construct(LoggerInterface $logger)
28
    {
29 2
        $this->logger = $logger;
30 2
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35 1
    public function startQuery($sql, array $params = null, array $types = null)
36
    {
37 1
        if (is_array($params)) {
38 1
            foreach ($params as $index => $param) {
39 1
                if (!is_string($params[$index])) {
40 1
                    continue;
41
                }
42
43
                // non utf-8 strings break json encoding
44 1
                if (!preg_match('//u', $params[$index])) {
45 1
                    $params[$index] = self::BINARY_DATA_VALUE;
46 1
                    continue;
47
                }
48
49 1
                if (self::MAX_STRING_LENGTH < mb_strlen($params[$index], 'UTF-8')) {
50 1
                    $params[$index] = mb_substr($params[$index], 0, self::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]';
51 1
                    continue;
52
                }
53
            }
54
        }
55
56 1
        if (null !== $this->logger) {
57 1
            $this->log($sql, null === $params ? array() : $params);
58
        }
59 1
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 1
    public function stopQuery()
65
    {
66 1
    }
67
68
    /**
69
     * Logs a message.
70
     *
71
     * @param string $message A message to log
72
     * @param array  $params  The context
73
     */
74 1
    private function log($message, array $params)
75
    {
76 1
        $this->logger->debug($message, $params);
77 1
    }
78
}
79