/
DoctrineExtension.php
352 lines (291 loc) · 10.4 KB
/
DoctrineExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<?php
namespace Doctrine\Bundle\DoctrineBundle\Twig;
use Doctrine\SqlFormatter\HtmlHighlighter;
use Doctrine\SqlFormatter\SqlFormatter;
use Symfony\Component\VarDumper\Cloner\Data;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
/**
* This class contains the needed functions in order to do the query highlighting
*/
class DoctrineExtension extends AbstractExtension
{
/**
* Number of maximum characters that one single line can hold in the interface
*
* @var int
*/
private $maxCharWidth = 100;
/**
* Define our functions
*
* @return TwigFilter[]
*/
public function getFilters()
{
return [
new TwigFilter('doctrine_minify_query', [$this, 'minifyQuery'], ['deprecated' => true]),
new TwigFilter('doctrine_pretty_query', [$this, 'formatQuery'], ['is_safe' => ['html']]),
new TwigFilter('doctrine_replace_query_parameters', [$this, 'replaceQueryParameters']),
];
}
/**
* Get the possible combinations of elements from the given array
*
* @param array $elements
* @param int $combinationsLevel
*
* @return array
*/
private function getPossibleCombinations(array $elements, $combinationsLevel)
{
$baseCount = count($elements);
$result = [];
if ($combinationsLevel === 1) {
foreach ($elements as $element) {
$result[] = [$element];
}
return $result;
}
$nextLevelElements = $this->getPossibleCombinations($elements, $combinationsLevel - 1);
foreach ($nextLevelElements as $nextLevelElement) {
$lastElement = $nextLevelElement[$combinationsLevel - 2];
$found = false;
foreach ($elements as $key => $element) {
if ($element === $lastElement) {
$found = true;
continue;
}
if ($found !== true || $key >= $baseCount) {
continue;
}
$tmp = $nextLevelElement;
$newCombination = array_slice($tmp, 0);
$newCombination[] = $element;
$result[] = array_slice($newCombination, 0);
}
}
return $result;
}
/**
* Shrink the values of parameters from a combination
*
* @param array $parameters
* @param array $combination
*
* @return string
*/
private function shrinkParameters(array $parameters, array $combination)
{
array_shift($parameters);
$result = '';
$maxLength = $this->maxCharWidth;
$maxLength -= count($parameters) * 5;
$maxLength /= count($parameters);
foreach ($parameters as $key => $value) {
$isLarger = false;
if (strlen($value) > $maxLength) {
$value = wordwrap($value, $maxLength, "\n", true);
$value = explode("\n", $value);
$value = $value[0];
$isLarger = true;
}
$value = self::escapeFunction($value);
if (! is_numeric($value)) {
$value = substr($value, 1, -1);
}
if ($isLarger) {
$value .= ' [...]';
}
$result .= ' ' . $combination[$key] . ' ' . $value;
}
return trim($result);
}
/**
* Attempt to compose the best scenario minified query so that a user could find it without expanding it
*
* @param string $query
* @param array $keywords
* @param int $required
*
* @return string
*/
private function composeMiniQuery($query, array $keywords, $required)
{
// Extract the mandatory keywords and consider the rest as optional keywords
$mandatoryKeywords = array_splice($keywords, 0, $required);
$combinations = [];
$combinationsCount = count($keywords);
// Compute all the possible combinations of keywords to match the query for
while ($combinationsCount > 0) {
$combinations = array_merge($combinations, $this->getPossibleCombinations($keywords, $combinationsCount));
$combinationsCount--;
}
// Try and match the best case query pattern
foreach ($combinations as $combination) {
$combination = array_merge($mandatoryKeywords, $combination);
$regexp = implode('(.*) ', $combination) . ' (.*)';
$regexp = '/^' . $regexp . '/is';
if (preg_match($regexp, $query, $matches)) {
return $this->shrinkParameters($matches, $combination);
}
}
// Try and match the simplest query form that contains only the mandatory keywords
$regexp = implode(' (.*)', $mandatoryKeywords) . ' (.*)';
$regexp = '/^' . $regexp . '/is';
if (preg_match($regexp, $query, $matches)) {
return $this->shrinkParameters($matches, $mandatoryKeywords);
}
// Fallback in case we didn't managed to find any good match (can we actually have that happen?!)
return substr($query, 0, $this->maxCharWidth);
}
/**
* Minify the query
*
* @param string $query
*
* @return string
*/
public function minifyQuery($query)
{
$result = '';
$keywords = [];
$required = 1;
// Check if we can match the query against any of the major types
switch (true) {
case stripos($query, 'SELECT') !== false:
$keywords = ['SELECT', 'FROM', 'WHERE', 'HAVING', 'ORDER BY', 'LIMIT'];
$required = 2;
break;
case stripos($query, 'DELETE') !== false:
$keywords = ['DELETE', 'FROM', 'WHERE', 'ORDER BY', 'LIMIT'];
$required = 2;
break;
case stripos($query, 'UPDATE') !== false:
$keywords = ['UPDATE', 'SET', 'WHERE', 'ORDER BY', 'LIMIT'];
$required = 2;
break;
case stripos($query, 'INSERT') !== false:
$keywords = ['INSERT', 'INTO', 'VALUE', 'VALUES'];
$required = 2;
break;
// If there's no match so far just truncate it to the maximum allowed by the interface
default:
$result = substr($query, 0, $this->maxCharWidth);
}
// If we had a match then we should minify it
if ($result === '') {
$result = $this->composeMiniQuery($query, $keywords, $required);
}
return $result;
}
/**
* Escape parameters of a SQL query
* DON'T USE THIS FUNCTION OUTSIDE ITS INTENDED SCOPE
*
* @internal
*
* @param mixed $parameter
*
* @return string
*/
public static function escapeFunction($parameter)
{
$result = $parameter;
switch (true) {
// Check if result is non-unicode string using PCRE_UTF8 modifier
case is_string($result) && ! preg_match('//u', $result):
$result = '0x' . strtoupper(bin2hex($result));
break;
case is_string($result):
$result = "'" . addslashes($result) . "'";
break;
case is_array($result):
foreach ($result as &$value) {
$value = static::escapeFunction($value);
}
$result = implode(', ', $result);
break;
case is_object($result):
$result = addslashes((string) $result);
break;
case $result === null:
$result = 'NULL';
break;
case is_bool($result):
$result = $result ? '1' : '0';
break;
}
return $result;
}
/**
* Return a query with the parameters replaced
*
* @param string $query
* @param array|Data $parameters
*
* @return string
*/
public function replaceQueryParameters($query, $parameters)
{
if ($parameters instanceof Data) {
$parameters = $parameters->getValue(true);
}
$i = 0;
if (! array_key_exists(0, $parameters) && array_key_exists(1, $parameters)) {
$i = 1;
}
return preg_replace_callback(
'/\?|((?<!:):[a-z0-9_]+)/i',
static function ($matches) use ($parameters, &$i) {
$key = substr($matches[0], 1);
if (! array_key_exists($i, $parameters) && ($key === false || ! array_key_exists($key, $parameters))) {
return $matches[0];
}
$value = array_key_exists($i, $parameters) ? $parameters[$i] : $parameters[$key];
$result = DoctrineExtension::escapeFunction($value);
$i++;
return $result;
},
$query
);
}
/**
* Formats and/or highlights the given SQL statement.
*
* @param string $sql
* @param bool $highlightOnly If true the query is not formatted, just highlighted
*
* @return string
*/
public function formatQuery($sql, $highlightOnly = false)
{
$sqlFormatter = new SqlFormatter(new HtmlHighlighter([
HtmlHighlighter::HIGHLIGHT_QUOTE => 'class="string"',
HtmlHighlighter::HIGHLIGHT_BACKTICK_QUOTE => 'class="string"',
HtmlHighlighter::HIGHLIGHT_RESERVED => 'class="keyword"',
HtmlHighlighter::HIGHLIGHT_BOUNDARY => 'class="symbol"',
HtmlHighlighter::HIGHLIGHT_NUMBER => 'class="number"',
HtmlHighlighter::HIGHLIGHT_WORD => 'class="word"',
HtmlHighlighter::HIGHLIGHT_ERROR => 'class="error"',
HtmlHighlighter::HIGHLIGHT_COMMENT => 'class="comment"',
HtmlHighlighter::HIGHLIGHT_VARIABLE => 'class="variable"',
], false));
if ($highlightOnly) {
return $sqlFormatter->highlight($sql);
}
return sprintf(
'<div class="highlight highlight-sql"><pre>%s</pre></div>',
$sqlFormatter->format($sql)
);
}
/**
* Get the name of the extension
*
* @return string
*/
public function getName()
{
return 'doctrine_extension';
}
}