Test Setup Failed
Push — master ( 42e323...580240 )
by Dominik
03:08
created

DoctrineDbalLogger   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 13
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 73
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
D startQuery() 0 33 10
A stopQuery() 0 3 1
A log() 0 4 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
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
    protected $logger;
23
24
    /**
25
     * @param LoggerInterface $logger
26
     */
27
    public function __construct(LoggerInterface $logger = null)
28
    {
29
        $this->logger = $logger;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function startQuery($sql, array $params = null, array $types = null)
36
    {
37
        if (is_array($params)) {
38
            foreach ($params as $index => $param) {
39
                if (!is_string($params[$index])) {
40
                    continue;
41
                }
42
43
                // non utf-8 strings break json encoding
44
                if (!preg_match('//u', $params[$index])) {
45
                    $params[$index] = self::BINARY_DATA_VALUE;
46
                    continue;
47
                }
48
49
                // detect if the too long string must be shorten
50
                if (function_exists('mb_strlen')) {
51
                    if (self::MAX_STRING_LENGTH < mb_strlen($params[$index], 'UTF-8')) {
52
                        $params[$index] = mb_substr($params[$index], 0, self::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]';
53
                        continue;
54
                    }
55
                } else {
56
                    if (self::MAX_STRING_LENGTH < strlen($params[$index])) {
57
                        $params[$index] = substr($params[$index], 0, self::MAX_STRING_LENGTH - 6).' [...]';
58
                        continue;
59
                    }
60
                }
61
            }
62
        }
63
64
        if (null !== $this->logger) {
65
            $this->log($sql, null === $params ? array() : $params);
66
        }
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function stopQuery()
73
    {
74
    }
75
76
    /**
77
     * Logs a message.
78
     *
79
     * @param string $message A message to log
80
     * @param array  $params  The context
81
     */
82
    private function log($message, array $params)
83
    {
84
        $this->logger->debug($message, $params);
85
    }
86
}
87