1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Rostenkowski\Doctrine\Debugger; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class SimpleQueryColorizer |
7
|
|
|
{ |
8
|
|
|
|
9
|
|
|
private static $keywords = [ |
10
|
|
|
'DROP TABLE', |
11
|
|
|
'CREATE TABLE', |
12
|
|
|
'PRAGMA', |
13
|
|
|
'SELECT', |
14
|
|
|
'FROM', |
15
|
|
|
'WHERE', |
16
|
|
|
'ORDER BY', |
17
|
|
|
'GROUP BY', |
18
|
|
|
'LEFT JOIN', |
19
|
|
|
'INNER JOIN', |
20
|
|
|
'UNION ALL', |
21
|
|
|
'AND', |
22
|
|
|
'OR', |
23
|
|
|
'UPDATE', |
24
|
|
|
'INSERT', |
25
|
|
|
'DELETE', |
26
|
|
|
'START TRANSACTION', |
27
|
|
|
'COMMIT', |
28
|
|
|
'INTO', |
29
|
|
|
'SET', |
30
|
|
|
'VALUES', |
31
|
|
|
'DEFAULT', |
32
|
|
|
'PRIMARY KEY', |
33
|
|
|
'VARCHAR', |
34
|
|
|
'INTEGER', |
35
|
|
|
'TEXT', |
36
|
|
|
'IN', |
37
|
|
|
'IS', |
38
|
|
|
'NULL', |
39
|
|
|
'NOT NULL', |
40
|
|
|
]; |
41
|
|
|
|
42
|
|
|
private static $newline = [ |
43
|
|
|
'SELECT', |
44
|
|
|
'FROM', |
45
|
|
|
'WHERE', |
46
|
|
|
'ORDER BY', |
47
|
|
|
'GROUP BY', |
48
|
|
|
'LEFT JOIN', |
49
|
|
|
'INNER JOIN', |
50
|
|
|
'UNION ALL', |
51
|
|
|
'AND', |
52
|
|
|
'OR', |
53
|
|
|
]; |
54
|
|
|
|
55
|
|
|
private static $keywordRegex; |
56
|
|
|
|
57
|
|
|
private static $newlineRegex; |
58
|
|
|
|
59
|
|
|
|
60
|
|
|
public function __construct() |
61
|
|
|
{ |
62
|
|
|
self::$keywordRegex = '/\b(' . implode('|', self::$keywords) . ')\b/'; |
63
|
|
|
self::$newlineRegex = '/\b(' . implode('|', self::$newline) . ')\b/'; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
|
67
|
|
|
public function colorize(string $sql, bool $format = false): string |
68
|
|
|
{ |
69
|
|
|
if ($format) { |
70
|
|
|
$sql = $this->format($sql); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
// each query type has custom colors |
74
|
|
|
$type = strtolower(substr($sql, 0, 6)); |
75
|
|
|
if (!in_array($type, ['select', 'update', 'delete', 'insert'])) { |
76
|
|
|
$type = ''; |
77
|
|
|
} |
78
|
|
|
$template = '<span class="reserved">$1</span>'; |
79
|
|
|
$sql = preg_replace(self::$keywordRegex, $template, $sql); |
80
|
|
|
|
81
|
|
|
return "<div class='query $type'>$sql</div>"; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
public function format(string $sql): string |
86
|
|
|
{ |
87
|
|
|
$template = '<br>$1'; |
88
|
|
|
$sql = preg_replace(self::$newlineRegex, $template, $sql); |
89
|
|
|
|
90
|
|
|
if (substr($sql, 0, 4) === '<br>') { |
91
|
|
|
$sql = substr($sql, 4); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
return $sql; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|