77use Illuminate \Support \Facades \DB ;
88use KitLoong \AppLogger \QueryLog \LogWriter as QueryLogger ;
99use Log ;
10+ use Event ;
11+ use Str ;
1012
1113class LaravelRequestDocsMiddleware extends QueryLogger
1214{
1315 private array $ queries = [];
1416 private array $ logs = [];
17+ private array $ models = [];
1518
1619 public function handle ($ request , Closure $ next )
1720 {
1821 if (!$ request ->headers ->has ('X-Request-LRD ' ) || !config ('app.debug ' )) {
1922 return $ next ($ request );
2023 }
2124
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+
2435 $ response = $ next ($ request );
2536
2637 try {
@@ -34,6 +45,7 @@ public function handle($request, Closure $next)
3445 $ content ->_lrd = [
3546 'queries ' => $ this ->queries ,
3647 'logs ' => $ this ->logs ,
48+ 'models ' => $ this ->models ,
3749 'memory ' => (string ) round (memory_get_peak_usage (true ) / 1048576 , 2 ) . "MB " ,
3850 ];
3951 $ jsonContent = json_encode ($ content );
@@ -51,7 +63,7 @@ public function handle($request, Closure $next)
5163 return $ response ;
5264 }
5365
54- public function listenDB ()
66+ public function listenToDB ()
5567 {
5668 DB ::listen (function (QueryExecuted $ query ) {
5769 $ this ->queries [] = $ this ->getMessages ($ query );
@@ -63,4 +75,34 @@ public function listenToLogs()
6375 $ this ->logs [] = $ message ;
6476 });
6577 }
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+ }
66108}
0 commit comments