Completed
Push — master ( ac629c...442bc4 )
by Robbie
9s
created

ProxyDBExtension::getQueries()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LeKoala\DebugBar\Extension;
4
5
use SqlFormatter;
6
use SilverStripe\ORM\DB;
7
use LeKoala\DebugBar\DebugBar;
8
use SilverStripe\Core\Extension;
9
use SilverStripe\Control\Controller;
10
use TractorCow\ClassProxy\Generators\ProxyGenerator;
11
12
class ProxyDBExtension extends Extension
13
{
14
    const MAX_FIND_SOURCE_LEVEL = 3;
15
16
    /**
17
     * Store queries
18
     *
19
     * @var array
20
     */
21
    protected static $queries = array();
22
23
    /**
24
     * Find source toggle (set by config find_source)
25
     *
26
     * @var boolean
27
     */
28
    protected static $findSource = true;
29
30
    public function updateProxy(ProxyGenerator &$proxy)
31
    {
32
        self::$findSource = DebugBar::config()->get('find_source');
33
34
        // In the closure, $this is the proxied database
35
        $callback = function ($args, $next) {
36
37
            // The first argument is always the sql query
38
            $sql = $args[0];
39
            $parameters = isset($args[2]) ? $args[2] : array();
40
41
            // Sql can be an array
42
            // TODO: verify if it's still the case in SS4
43
            if (is_array($sql)) {
44
                $parameters = $sql[1];
45
                $sql = $sql[0];
46
            }
47
48
            // Inline sql
49
            $sql = DB::inline_parameters($sql, $parameters);
50
51
            // Get time and memory for the request
52
            $startTime = microtime(true);
53
            $startMemory = memory_get_usage(true);
54
55
            // Execute all middleware
56
            $handle = $next(...$args);
57
58
            // Get time and memory after the request
59
            $endTime = microtime(true);
60
            $endMemory = memory_get_usage(true);
61
62
            // Show query on screen
63
            if (DebugBar::getShowQueries()) {
64
                $formattedSql = SqlFormatter::format($sql);
65
                $rows = $handle->numRecords();
66
67
                echo '<pre>The following query took <b>' . round($endTime - $startTime, 4) . '</b>s an returned <b>' . $rows . "</b> row(s) \n";
68
                echo 'Triggered by: <i>' . self::findSource() . '</i></pre>';
69
                echo $formattedSql;
70
71
                // Preview results
72
                $results = iterator_to_array($handle);
73
                if ($rows > 0) {
74
                    if ($rows == 1) {
75
                        dump($results[0]);
76
                    } else {
77
                        $linearValues = count($results[0]);
78
                        if ($linearValues) {
79
                            dump(implode(
80
                                ',',
81
                                array_map(
82
                                    function ($item) {
83
                                        return $item[key($item)];
84
                                    },
85
                                    $results
86
                                )
87
                            ));
88
                        } else {
89
                            if ($rows < 20) {
90
                                dump($results);
91
                            } else {
92
                                dump("Too many results to display");
93
                            }
94
                        }
95
                    }
96
                }
97
                echo '<hr/>';
98
99
                $handle->rewind(); // Rewind the results
100
            }
101
102
            // Sometimes, ugly spaces are there
103
            $sql = preg_replace('/[[:blank:]]+/', ' ', trim($sql));
104
105
            // Sometimes, the select statement can be very long and unreadable
106
            $shortsql = $sql;
107
            $matches = null;
108
            preg_match_all('/SELECT(.+?) FROM/is', $sql, $matches);
109
            $select = empty($matches[1]) ? null : trim($matches[1][0]);
110
            if (strlen($select) > 100) {
111
                $shortsql = str_replace($select, '"ClickToShowFields"', $sql);
112
            } else {
113
                $select = null;
114
            }
115
116
            self::$queries[] = array(
117
                'short_query' => $shortsql,
118
                'select' => $select,
119
                'query' => $sql,
120
                'start_time' => $startTime,
121
                'end_time' => $endTime,
122
                'duration' => $endTime - $startTime,
123
                'memory' => $endMemory - $startMemory,
124
                'rows' => $handle ? $handle->numRecords() : null,
125
                'success' => $handle ? true : false,
126
                'database' => $this->getSelectedDatabase(),
0 ignored issues
show
Bug introduced by
The method getSelectedDatabase() does not exist on LeKoala\DebugBar\Extension\ProxyDBExtension. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

126
                'database' => $this->/** @scrutinizer ignore-call */ getSelectedDatabase(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
127
                'source' => self::$findSource ? self::findSource() : null
128
            );
129
130
            return $handle;
131
        };
132
133
        // Attach to benchmarkQuery to fire on both query and preparedQuery
134
        $proxy = $proxy->addMethod('benchmarkQuery', $callback);
135
    }
136
137
    public static function getQueries()
138
    {
139
        return self::$queries;
140
    }
141
142
    protected static function findSource()
143
    {
144
        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT);
145
146
        // Not relevant to determine source
147
        $internalClasses = array(
148
            '',
149
            get_called_class(),
150
            // DebugBar
151
            DebugBar::class,
152
            \LeKoala\DebugBar\Middleware\DebugBarMiddleware::class,
153
            // Proxy
154
            ProxyDBExtension::class,
155
            \TractorCow\ClassProxy\Proxied\ProxiedBehaviour::class,
156
            // Orm
157
            \SilverStripe\ORM\Connect\Database::class,
158
            \SilverStripe\ORM\Connect\DBSchemaManager::class,
159
            \SilverStripe\ORM\Connect\MySQLDatabase::class,
160
            \SilverStripe\ORM\Connect\MySQLSchemaManager::class,
161
            \SilverStripe\ORM\DataObjectSchema::class,
162
            \SilverStripe\ORM\DB::class,
163
            \SilverStripe\ORM\Queries\SQLExpression::class,
164
            \SilverStripe\ORM\DataList::class,
165
            \SilverStripe\ORM\DataObject::class,
166
            \SilverStripe\ORM\DataQuery::class,
167
            \SilverStripe\ORM\Queries\SQLSelect::class,
168
            \SilverStripe\ORM\Map::class,
169
            \SilverStripe\ORM\ListDecorator::class,
170
            // Core
171
            \SilverStripe\Control\Director::class,
172
        );
173
174
        $viewerClasses = array(
175
            \SilverStripe\View\SSViewer_DataPresenter::class,
176
            \SilverStripe\View\SSViewer_Scope::class,
177
            \SilverStripe\View\SSViewer::class,
178
            \SilverStripe\View\ViewableData::class
179
        );
180
181
        $sources = array();
182
        foreach ($traces as $trace) {
183
            $class = isset($trace['class']) ? $trace['class'] : null;
184
            $line = isset($trace['line']) ? $trace['line'] : null;
185
            $function = isset($trace['function']) ? $trace['function'] : null;
186
            $type = isset($trace['type']) ? $trace['type'] : '::';
187
188
            /* @var $object SSViewer */
189
            $object = isset($trace['object']) ? $trace['object'] : null;
190
191
            if (in_array($class, $internalClasses)) {
192
                continue;
193
            }
194
195
            // Viewer classes need special handling
196
            if (in_array($class, $viewerClasses)) {
197
                if ($function == 'includeGeneratedTemplate') {
198
                    $templates = $object->templates();
199
200
                    $template = null;
201
                    if (isset($templates['main'])) {
202
                        $template = basename($templates['main']);
203
                    } else {
204
                        $keys = array_keys($templates);
205
                        $key = reset($keys);
206
                        if (isset($templates[$key])) {
207
                            $template = $key . ':' . basename($templates[$key]);
208
                        }
209
                    }
210
                    if (!empty($template)) {
211
                        $sources[] = $template;
212
                    }
213
                }
214
                continue;
215
            }
216
217
            $name = $class;
218
            if ($class && !DebugBar::config()->get('show_namespaces')) {
219
                $nameArray = explode("\\", $class);
220
                $name = array_pop($nameArray);
221
            }
222
            if ($function) {
223
                $name .= $type . $function;
224
            }
225
            if ($line) {
226
                $name .= ':' . $line;
227
            }
228
229
            $sources[] = $name;
230
231
            if (count($sources) > self::MAX_FIND_SOURCE_LEVEL) {
232
                break;
233
            }
234
235
            // We reached a Controller, exit loop
236
            if ($object && $object instanceof Controller) {
237
                break;
238
            }
239
        }
240
241
        if (empty($sources)) {
242
            return 'Undefined source';
243
        }
244
        return implode(' > ', $sources);
245
    }
246
247
}
248