ProxyDBExtension   A
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 273
Duplicated Lines 0 %

Importance

Changes 7
Bugs 2 Features 0
Metric Value
eloc 142
c 7
b 2
f 0
dl 0
loc 273
rs 9.1199
wmc 41

4 Methods

Rating   Name   Duplication   Size   Complexity  
A resetQueries() 0 3 1
C updateProxy() 0 109 14
F findSource() 0 117 25
A getQueries() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like ProxyDBExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ProxyDBExtension, and based on these observations, apply Extract Interface, too.

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<array<mixed>>
20
     */
21
    protected static $queries = [];
22
23
    /**
24
     * Find source toggle (set by config find_source)
25
     *
26
     * @var boolean
27
     */
28
    protected static $findSource = true;
29
30
    /**
31
     * @param ProxyGenerator $proxy
32
     * @return void
33
     */
34
    public function updateProxy(ProxyGenerator &$proxy)
35
    {
36
        self::$findSource = DebugBar::config()->get('find_source');
37
38
        // In the closure, $this is the proxied database
39
        $callback = function ($args, $next) {
40
41
            // The first argument is always the sql query
42
            $sql = $args[0];
43
            $parameters = isset($args[2]) ? $args[2] : [];
44
45
            // Sql can be an array
46
            if (is_array($sql)) {
47
                $parameters = $sql[1];
48
                $sql = $sql[0];
49
            }
50
51
            // Inline sql
52
            $sql = DB::inline_parameters($sql, $parameters);
53
54
            // Get time and memory for the request
55
            $startTime = microtime(true);
56
            $startMemory = memory_get_usage(true);
57
58
            // Execute all middleware
59
            $handle = $next(...$args);
60
61
            // Get time and memory after the request
62
            $endTime = microtime(true);
63
            $endMemory = memory_get_usage(true);
64
65
            // Show query on screen
66
            if (DebugBar::getShowQueries()) {
67
                $formattedSql = SqlFormatter::format($sql);
68
                $rows = $handle->numRecords();
69
70
                echo '<pre>The following query took <b>' . round($endTime - $startTime, 4) . '</b>s an returned <b>' . $rows . "</b> row(s) \n";
71
                echo 'Triggered by: <i>' . self::findSource() . '</i></pre>';
72
                echo $formattedSql;
73
74
                // Preview results
75
                $results = iterator_to_array($handle);
76
                if ($rows > 0) {
77
                    if ($rows == 1) {
78
                        dump($results[0]);
79
                    } else {
80
                        $linearValues = count($results[0]);
81
                        if ($linearValues) {
82
                            dump(implode(
83
                                ',',
84
                                array_map(
85
                                    function ($item) {
86
                                        return $item[key($item)];
87
                                    },
88
                                    $results
89
                                )
90
                            ));
91
                        } else {
92
                            if ($rows < 20) {
93
                                dump($results);
94
                            } else {
95
                                dump("Too many results to display");
96
                            }
97
                        }
98
                    }
99
                }
100
                echo '<hr/>';
101
102
                $handle->rewind(); // Rewind the results
103
            }
104
105
            // Sometimes, ugly spaces are there
106
            $sql = preg_replace('/[[:blank:]]+/', ' ', trim($sql));
107
108
            // Sometimes, the select statement can be very long and unreadable
109
            $shortsql = $sql;
110
            $matches = null;
111
            preg_match_all('/SELECT(.+?) FROM/is', $sql, $matches);
112
            $select = empty($matches[1]) ? null : trim($matches[1][0]);
113
            if ($select !== null) {
114
                if (strlen($select) > 100) {
115
                    $shortsql = str_replace($select, '"ClickToShowFields"', $sql);
116
                } else {
117
                    $select = null;
118
                }
119
            }
120
121
            // null on the first query, since it's the select statement itself
122
            $db = DB::get_conn()->getSelectedDatabase();
123
124
            self::$queries[] = array(
125
                'short_query' => $shortsql,
126
                'select' => $select,
127
                'query' => $sql,
128
                'start_time' => $startTime,
129
                'end_time' => $endTime,
130
                'duration' => $endTime - $startTime,
131
                'memory' => $endMemory - $startMemory,
132
                'rows' => $handle ? $handle->numRecords() : null,
133
                'success' => $handle ? true : false,
134
                'database' => $db,
135
                'source' => self::$findSource ? self::findSource() : null
136
            );
137
138
            return $handle;
139
        };
140
141
        // Attach to benchmarkQuery to fire on both query and preparedQuery
142
        $proxy = $proxy->addMethod('benchmarkQuery', $callback);
143
    }
144
145
    /**
146
     * Reset queries array
147
     *
148
     * Helpful for long running process and avoid accumulating queries
149
     *
150
     * @return void
151
     */
152
    public static function resetQueries()
153
    {
154
        self::$queries = [];
155
    }
156
157
    /**
158
     * @return array<array<mixed>>
159
     */
160
    public static function getQueries()
161
    {
162
        return self::$queries;
163
    }
164
165
    /**
166
     * @return string
167
     */
168
    protected static function findSource()
169
    {
170
        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT);
171
172
        // Not relevant to determine source
173
        $internalClasses = array(
174
            '',
175
            get_called_class(),
176
            // DebugBar
177
            DebugBar::class,
178
            \LeKoala\DebugBar\Middleware\DebugBarMiddleware::class,
179
            // Proxy
180
            ProxyDBExtension::class,
181
            \TractorCow\ClassProxy\Proxied\ProxiedBehaviour::class,
182
            // Orm
183
            \SilverStripe\ORM\Connect\Database::class,
184
            \SilverStripe\ORM\Connect\DBSchemaManager::class,
185
            \SilverStripe\ORM\Connect\MySQLDatabase::class,
186
            \SilverStripe\ORM\Connect\MySQLSchemaManager::class,
187
            \SilverStripe\ORM\DataObjectSchema::class,
188
            \SilverStripe\ORM\DB::class,
189
            \SilverStripe\ORM\Queries\SQLExpression::class,
190
            \SilverStripe\ORM\DataList::class,
191
            \SilverStripe\ORM\DataObject::class,
192
            \SilverStripe\ORM\DataQuery::class,
193
            \SilverStripe\ORM\Queries\SQLSelect::class,
194
            \SilverStripe\ORM\Map::class,
195
            \SilverStripe\ORM\ListDecorator::class,
196
            // Core
197
            \SilverStripe\Control\Director::class,
198
        );
199
200
        $viewerClasses = array(
201
            \SilverStripe\View\SSViewer_DataPresenter::class,
202
            \SilverStripe\View\SSViewer_Scope::class,
0 ignored issues
show
Bug introduced by
The type SilverStripe\View\SSViewer_Scope was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
203
            \SilverStripe\View\SSViewer::class,
204
            \LeKoala\DebugBar\Proxy\SSViewerProxy::class,
205
            \SilverStripe\View\ViewableData::class
206
        );
207
208
        $sources = [];
209
        foreach ($traces as $i => $trace) {
210
            // We need to be able to look ahead one item in the trace, because the class/function values
211
            // are talking about what is being *called* on this line, not the function this line lives in.
212
            if (!isset($traces[$i + 1])) {
213
                break;
214
            }
215
216
            $file = isset($trace['file']) ? pathinfo($trace['file'], PATHINFO_FILENAME) : null;
217
            $class = isset($traces[$i + 1]['class']) ? $traces[$i + 1]['class'] : null;
218
            $line = isset($trace['line']) ? $trace['line'] : null;
219
            $function = isset($traces[$i + 1]['function']) ? $traces[$i + 1]['function'] : null;
220
            $type = isset($traces[$i + 1]['type']) ? $traces[$i + 1]['type'] : '::';
221
222
            /* @var $object SSViewer */
223
            $object = isset($traces[$i + 1]['object']) ? $traces[$i + 1]['object'] : null;
224
225
            if (in_array($class, $internalClasses)) {
226
                continue;
227
            }
228
229
            // Viewer classes need special handling
230
            if (in_array($class, $viewerClasses)) {
231
                if ($function == 'includeGeneratedTemplate') {
232
                    $templates = $object->templates();
233
234
                    $template = null;
235
                    if (isset($templates['main'])) {
236
                        $template = basename($templates['main']);
237
                    } else {
238
                        $keys = array_keys($templates);
239
                        $key = reset($keys);
240
                        if (isset($templates[$key])) {
241
                            $template = $key . ':' . basename($templates[$key]);
242
                        }
243
                    }
244
                    if (!empty($template)) {
245
                        $sources[] = $template;
246
                    }
247
                }
248
                continue;
249
            }
250
251
            $name = $class;
252
            if ($class && !DebugBar::config()->get('show_namespaces')) {
253
                $nameArray = explode("\\", $class);
254
                $name = array_pop($nameArray);
255
256
                // Maybe we are inside a trait?
257
                if ($file && $file != $name) {
258
                    $name .= '(' . $file . ')';
0 ignored issues
show
Bug introduced by
Are you sure $file of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

258
                    $name .= '(' . /** @scrutinizer ignore-type */ $file . ')';
Loading history...
259
                }
260
            }
261
            if ($function) {
262
                $name .= $type . $function;
263
            }
264
            if ($line) {
265
                // Line number could apply to a trait
266
                $name .= ':' . $line;
267
            }
268
269
            $sources[] = $name;
270
271
            if (count($sources) > self::MAX_FIND_SOURCE_LEVEL) {
272
                break;
273
            }
274
275
            // We reached a Controller, exit loop
276
            if ($object && $object instanceof Controller) {
277
                break;
278
            }
279
        }
280
281
        if (empty($sources)) {
282
            return 'Undefined source';
283
        }
284
        return implode(' > ', $sources);
285
    }
286
}
287