7
7
use Illuminate \Support \Facades \DB ;
8
8
use KitLoong \AppLogger \QueryLog \LogWriter as QueryLogger ;
9
9
use Log ;
10
+ use Event ;
11
+ use Str ;
10
12
11
13
class LaravelRequestDocsMiddleware extends QueryLogger
12
14
{
13
15
private array $ queries = [];
14
16
private array $ logs = [];
17
+ private array $ models = [];
15
18
16
19
public function handle ($ request , Closure $ next )
17
20
{
18
21
if (!$ request ->headers ->has ('X-Request-LRD ' ) || !config ('app.debug ' )) {
19
22
return $ next ($ request );
20
23
}
21
24
22
- $ this ->listenDB ();
23
- $ this ->listenToLogs ();
25
+ if (!config ('request-docs.hide_sql_data ' )) {
26
+ $ this ->listenToDB ();
27
+ }
28
+ if (!config ('request-docs.hide_logs_data ' )) {
29
+ $ this ->listenToLogs ();
30
+ }
31
+ if (!config ('request-docs.hide_models_data ' )) {
32
+ $ this ->listenToModels ();
33
+ }
34
+
24
35
$ response = $ next ($ request );
25
36
26
37
try {
@@ -34,6 +45,7 @@ public function handle($request, Closure $next)
34
45
$ content ->_lrd = [
35
46
'queries ' => $ this ->queries ,
36
47
'logs ' => $ this ->logs ,
48
+ 'models ' => $ this ->models ,
37
49
'memory ' => (string ) round (memory_get_peak_usage (true ) / 1048576 , 2 ) . "MB " ,
38
50
];
39
51
$ jsonContent = json_encode ($ content );
@@ -51,7 +63,7 @@ public function handle($request, Closure $next)
51
63
return $ response ;
52
64
}
53
65
54
- public function listenDB ()
66
+ public function listenToDB ()
55
67
{
56
68
DB ::listen (function (QueryExecuted $ query ) {
57
69
$ this ->queries [] = $ this ->getMessages ($ query );
@@ -63,4 +75,34 @@ public function listenToLogs()
63
75
$ this ->logs [] = $ message ;
64
76
});
65
77
}
78
+
79
+ public function listenToModels ()
80
+ {
81
+ Event::listen ('eloquent.* ' , function ($ event , $ models ) {
82
+ foreach (array_filter ($ models ) as $ model ) {
83
+ // doing and booted ignore
84
+ if (Str::startsWith ($ event , 'eloquent.booting ' )
85
+ || Str::startsWith ($ event , 'eloquent.retrieving ' )
86
+ || Str::startsWith ($ event , 'eloquent.creating ' )
87
+ || Str::startsWith ($ event , 'eloquent.saving ' )
88
+ || Str::startsWith ($ event , 'eloquent.updating ' )
89
+ || Str::startsWith ($ event , 'eloquent.deleting ' )
90
+ ) {
91
+ continue ;
92
+ }
93
+ // split $event by : and take first part
94
+ $ event = explode (': ' , $ event )[0 ];
95
+ $ event = Str::replace ('eloquent. ' , '' , $ event );
96
+ $ class = get_class ($ model );
97
+
98
+ if (!isset ($ this ->models [$ class ])) {
99
+ $ this ->models [$ class ] = [];
100
+ }
101
+ if (!isset ($ this ->models [$ class ][$ event ])) {
102
+ $ this ->models [$ class ][$ event ] = 0 ;
103
+ }
104
+ $ this ->models [$ class ][$ event ] = $ this ->models [$ class ][$ event ]+1 ;
105
+ }
106
+ });
107
+ }
66
108
}
0 commit comments