-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathQueryDetector.php
More file actions
executable file
·264 lines (213 loc) · 6.99 KB
/
QueryDetector.php
File metadata and controls
executable file
·264 lines (213 loc) · 6.99 KB
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
<?php
namespace BeyondCode\QueryDetector;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Builder;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Database\Eloquent\Relations\Relation;
use BeyondCode\QueryDetector\Events\QueryDetected;
class QueryDetector
{
/** @var Collection */
private $queries;
/**
* @var bool
*/
private $booted = false;
/** @var int */
private $disabledDepth = 0;
private function resetQueries()
{
$this->queries = Collection::make();
}
public function __construct()
{
$this->resetQueries();
}
public function boot()
{
if ($this->booted) {
$this->resetQueries();
return;
}
DB::listen(function ($query) {
$backtrace = collect(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, config('querydetector.backtrace_limit', 50)));
$this->logQuery($query, $backtrace);
});
foreach ($this->getOutputTypes() as $outputType) {
app()->singleton($outputType);
app($outputType)->boot();
}
$this->booted = true;
}
public function isEnabled(): bool
{
$configEnabled = value(config('querydetector.enabled'));
if ($configEnabled === null) {
$configEnabled = config('app.debug');
}
return $configEnabled;
}
/**
* @template T
* @param callable(): T $callback
* @return T
*/
public function withoutDetection(callable $callback)
{
$this->disabledDepth++;
try {
return $callback();
} finally {
$this->disabledDepth--;
}
}
public function logQuery($query, Collection $backtrace)
{
if ($this->disabledDepth > 0) {
return;
}
$modelTrace = $backtrace->first(function ($trace) {
return Arr::get($trace, 'object') instanceof Builder;
});
// The query is coming from an Eloquent model
if (!is_null($modelTrace)) {
/*
* Relations get resolved by either calling the "getRelationValue" method on the model,
* or if the class itself is a Relation.
*/
$relation = $backtrace->first(function ($trace) {
return Arr::get($trace, 'function') === 'getRelationValue' || Arr::get($trace, 'class') === Relation::class;
});
// We try to access a relation
if (is_array($relation) && isset($relation['object'])) {
if ($relation['class'] === Relation::class) {
$model = get_class($relation['object']->getParent());
$relationName = get_class($relation['object']->getRelated());
$relatedModel = $relationName;
} else {
$model = get_class($relation['object']);
$relationName = $relation['args'][0];
$relatedModel = $relationName;
}
$sources = $this->findSource($backtrace);
if (empty($sources)) {
return;
}
$key = md5($query->sql . $model . $relationName . $sources[0]->name . $sources[0]->line);
$count = Arr::get($this->queries, $key . '.count', 0);
$time = Arr::get($this->queries, $key . '.time', 0);
$this->queries[$key] = [
'count' => ++$count,
'time' => $time + $query->time,
'query' => $query->sql,
'model' => $model,
'relatedModel' => $relatedModel,
'relation' => $relationName,
'sources' => $sources
];
}
}
}
protected function findSource($stack)
{
$sources = [];
foreach ($stack as $index => $trace) {
$sources[] = $this->parseTrace($index, $trace);
}
return array_values(array_filter($sources));
}
public function parseTrace($index, array $trace)
{
$frame = (object)[
'index' => $index,
'name' => null,
'line' => isset($trace['line']) ? $trace['line'] : '?',
];
if (isset($trace['class']) &&
isset($trace['file']) &&
!$this->fileIsInExcludedPath($trace['file'])
) {
$frame->name = $this->normalizeFilename($trace['file']);
return $frame;
}
return false;
}
/**
* Check if the given file is to be excluded from analysis
*
* @param string $file
* @return bool
*/
protected function fileIsInExcludedPath($file)
{
$excludedPaths = [
'/vendor/laravel/framework/src/Illuminate/Database',
'/vendor/laravel/framework/src/Illuminate/Events',
];
$normalizedPath = str_replace('\\', '/', $file);
foreach ($excludedPaths as $excludedPath) {
if (strpos($normalizedPath, $excludedPath) !== false) {
return true;
}
}
return false;
}
/**
* Shorten the path by removing the relative links and base dir
*
* @param string $path
* @return string
*/
protected function normalizeFilename($path): string
{
if (file_exists($path)) {
$path = realpath($path);
}
return str_replace(base_path(), '', $path);
}
public function getDetectedQueries(): Collection
{
$exceptions = config('querydetector.except', []);
$queries = $this->queries
->values();
foreach ($exceptions as $parentModel => $relations) {
foreach ($relations as $relation) {
$queries = $queries->reject(function ($query) use ($relation, $parentModel) {
return $query['model'] === $parentModel && $query['relatedModel'] === $relation;
});
}
}
$queries = $queries->where('count', '>', config('querydetector.threshold', 1))->values();
if ($queries->isNotEmpty()) {
event(new QueryDetected($queries));
}
return $queries;
}
protected function getOutputTypes()
{
$outputTypes = config('querydetector.output');
if (!is_array($outputTypes)) {
$outputTypes = [$outputTypes];
}
return $outputTypes;
}
protected function applyOutput(Response $response)
{
foreach ($this->getOutputTypes() as $type) {
app($type)->output($this->getDetectedQueries(), $response);
}
}
public function output($request, $response)
{
if ($this->getDetectedQueries()->isNotEmpty()) {
$this->applyOutput($response);
}
return $response;
}
public function emptyQueries()
{
$this->queries = Collection::make();
}
}