BufferedPSRLogger::flushTo()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 5
c 1
b 0
f 1
nc 1
nop 3
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 1
rs 10
1
<?php
2
3
namespace mindplay\sql\framework;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\Log\LogLevel;
7
8
/**
9
 * This class implements a buffered query logger.
10
 *
11
 * To flush recorded log-entries to a PSR-3 logger, call the `flushTo()` method, e.g. at
12
 * the end of an HTTP request.
13
 *
14
 * The queries are emitted in a `kodus/chrome-logger` compatible format.
15
 *
16
 * @link https://github.com/kodus/chrome-logger
17
 */
18
class BufferedPSRLogger implements Logger
19
{
20
    /**
21
     * @var array<string,mixed>[] buffered query log-entries
22
     */
23
    private array $entries = [];
24
25
    /**
26
     * Flush all recorded query log-entries to a single PSR-3 log-entry
27
     *
28
     * @param LoggerInterface $logger the PSR Logger to which the query-log will be flushed
29
     * @param string|mixed    $log_level PSR-3 log level (usually a string, defaults to "info")
30
     * @param string          $message   combined log entry title
31
     *
32
     * @see LogLevel
33
     */
34 1
    public function flushTo(LoggerInterface $logger, mixed $log_level = LogLevel::INFO, string $message = "INFO"): void
35
    {
36 1
        $logger->log(
37 1
            $log_level,
38 1
            $message,
39 1
            ["table: SQL Queries" => $this->entries]
40 1
        );
41
42 1
        $this->entries = [];
43
    }
44
45
    /**
46
     * @param array<string,mixed> $params
47
     */
48 1
    public function logQuery(string $sql, array $params, float $time_msec): void
49
    {
50 1
        $this->entries[] = [
51 1
            "time" => sprintf('%0.3f', $time_msec / 1000) . " s",
52 1
            "sql"  => QueryFormatter::formatQuery($sql, $params),
53 1
        ];
54
    }
55
}
56