|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* A reduced version of LeKoala\DebugBar\Extension\ProxyDBExtension |
|
4
|
|
|
*/ |
|
5
|
|
|
|
|
6
|
|
|
namespace Gurucomkz\EagerLoading\Tests; |
|
7
|
|
|
|
|
8
|
|
|
use SilverStripe\Core\Extension; |
|
9
|
|
|
use SilverStripe\ORM\DB; |
|
10
|
|
|
use TractorCow\ClassProxy\Generators\ProxyGenerator; |
|
11
|
|
|
|
|
12
|
|
|
class ProxyDBCounterExtension extends Extension |
|
13
|
|
|
{ |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Store queries |
|
17
|
|
|
* |
|
18
|
|
|
* @var array |
|
19
|
|
|
*/ |
|
20
|
|
|
protected static $queries = []; |
|
21
|
|
|
|
|
22
|
|
|
|
|
23
|
|
|
public function updateProxy(ProxyGenerator &$proxy) |
|
24
|
|
|
{ |
|
25
|
|
|
// In the closure, $this is the proxied database |
|
26
|
|
|
$callback = function ($args, $next) { |
|
27
|
|
|
|
|
28
|
|
|
// The first argument is always the sql query |
|
29
|
|
|
$sql = $args[0]; |
|
30
|
|
|
$parameters = isset($args[2]) ? $args[2] : []; |
|
31
|
|
|
|
|
32
|
|
|
// Sql can be an array |
|
33
|
|
|
// TODO: verify if it's still the case in SS4 |
|
34
|
|
|
if (is_array($sql)) { |
|
35
|
|
|
$parameters = $sql[1]; |
|
36
|
|
|
$sql = $sql[0]; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
// Inline sql |
|
40
|
|
|
$sql = DB::inline_parameters($sql, $parameters); |
|
41
|
|
|
|
|
42
|
|
|
// Execute all middleware |
|
43
|
|
|
$handle = $next(...$args); |
|
44
|
|
|
|
|
45
|
|
|
// Sometimes, ugly spaces are there |
|
46
|
|
|
$sql = preg_replace('/[[:blank:]]+/', ' ', trim($sql)); |
|
47
|
|
|
|
|
48
|
|
|
self::$queries[] = [ |
|
49
|
|
|
'query' => $sql, |
|
50
|
|
|
'rows' => $handle ? $handle->numRecords() : null, |
|
51
|
|
|
]; |
|
52
|
|
|
// echo "\nQuery: $sql\n"; |
|
53
|
|
|
|
|
54
|
|
|
return $handle; |
|
55
|
|
|
}; |
|
56
|
|
|
|
|
57
|
|
|
// Attach to benchmarkQuery to fire on both query and preparedQuery |
|
58
|
|
|
$proxy = $proxy->addMethod('benchmarkQuery', $callback); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public static function resetQueries() |
|
62
|
|
|
{ |
|
63
|
|
|
self::$queries = []; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
public static function getQueries() |
|
67
|
|
|
{ |
|
68
|
|
|
return self::$queries; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public static function getQueriesCount() |
|
72
|
|
|
{ |
|
73
|
|
|
return count(self::$queries); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|