Passed
Push — master ( 80d34d...67ed39 )
by Paul
02:55
created

Queries::sortByTime()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 3
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\BlackBar\Modules;
4
5
use GeminiLabs\BlackBar\Application;
6
7
class Queries extends Module
8
{
9
    public function entries(): array
10
    {
11
        global $wpdb;
12
        $entries = [];
13
        $index = 0;
14
        $search = [
15
            'FROM', 'GROUP BY', 'INNER JOIN', 'LEFT JOIN', 'LIMIT',
16
            'ON DUPLICATE KEY UPDATE', 'ORDER BY', 'OFFSET', ' SET', 'WHERE',
17
        ];
18
        $replace = array_map(function ($value) {
19
            return PHP_EOL.$value;
20
        }, $search);
21
        foreach ($wpdb->queries as $query) {
22
            $sql = preg_replace('/\s\s+/', ' ', trim($query[0]));
23
            $sql = str_replace(PHP_EOL, ' ', $sql);
24
            $sql = str_replace(['( ',' )',' ,'], ['(',')',','], $sql);
25
            $sql = str_replace($search, $replace, $sql);
26
            $parts = explode(PHP_EOL, $sql);
27
            $sql = array_reduce($parts, function ($carry, $part) {
28
                if (str_starts_with($part, 'SELECT') && strlen($part) > 100) {
29
                    $part = preg_replace('/\s*(,)\s*/', ','.PHP_EOL.'  ', $part);
30
                }
31
                if (str_starts_with($part, 'WHERE')) {
32
                    $part = str_replace('AND', PHP_EOL.'  AND', $part);
33
                }
34
                return $carry.$part.PHP_EOL;
35
            });
36
            $trace = explode(', ', $query[2]);
37
            $nanoseconds = (int) round($query[1] * 1e9);
38
            $entries[] = [
39
                'index' => $index++,
40
                'sql' => $sql,
41
                'time' => $nanoseconds,
42
                'time_formatted' => $this->formatTime($nanoseconds),
43
                'trace' => array_reverse($trace, true),
44
            ];
45
        }
46
        uasort($entries, [$this, 'sortByTime']);
47
        return $entries;
48
    }
49
50
    public function hasEntries(): bool
51
    {
52
        global $wpdb;
53
        return !empty($wpdb->queries);
54
    }
55
56
    public function info(): string
57
    {
58
        if (!defined('SAVEQUERIES') || !SAVEQUERIES) {
59
            return '';
60
        }
61
        global $wpdb;
62
        $seconds = (float) array_sum(wp_list_pluck($wpdb->queries, 1));
63
        $nanoseconds = (int) round($seconds * 1e9);
64
        return $this->formatTime($nanoseconds);
65
    }
66
67
    public function label(): string
68
    {
69
        return __('SQL', 'blackbar');
70
    }
71
72
    protected function sortByTime(array $a, array $b): int
73
    {
74
        if ($a['time'] !== $b['time']) {
75
            return ($a['time'] > $b['time']) ? -1 : 1;
76
        }
77
        return 0;
78
    }
79
}
80