44
55namespace CraftCms \Cms \View ;
66
7- use Craft ;
87use Illuminate \Container \Attributes \Scoped ;
98use Illuminate \Support \Facades \Auth ;
9+ use Illuminate \Support \Facades \Log ;
10+
11+ use function CraftCms \Cms \debugbar ;
1012
1113#[Scoped]
1214class TemplateProfiler
@@ -26,6 +28,9 @@ class TemplateProfiler
2628 /** @var array<string, array<string, int>> */
2729 private array $ profileCounters = [];
2830
31+ /** @var array<string, int> */
32+ private array $ timers = [];
33+
2934 public function beginProfile (string $ type , string $ name ): void
3035 {
3136 if (! $ this ->shouldProfile ()) {
@@ -38,7 +43,15 @@ public function beginProfile(string $type, string $name): void
3843 $ count = ++$ this ->profileCounters [$ type ][$ name ];
3944 }
4045
41- Craft::beginProfile ($ this ->profileToken ($ type , $ name , $ count ), 'Twig template ' );
46+ $ this ->timers [$ this ->profileToken ($ type , $ name , $ count )] = hrtime (true );
47+
48+ debugbar ()->startMeasure ($ this ->profileToken ($ type , $ name , $ count ), "{$ type } {$ name }" );
49+
50+ Log::debug ('profile begin ' , [
51+ 'name ' => $ name ,
52+ 'type ' => $ type ,
53+ 'count ' => $ count ,
54+ ]);
4255 }
4356
4457 public function endProfile (string $ type , string $ name ): void
@@ -48,7 +61,29 @@ public function endProfile(string $type, string $name): void
4861 }
4962
5063 $ count = $ this ->profileCounters [$ type ][$ name ]--;
51- Craft::endProfile ($ this ->profileToken ($ type , $ name , $ count ), 'Twig template ' );
64+
65+ debugbar ()->stopMeasure ($ this ->profileToken ($ type , $ name , $ count ));
66+
67+ $ start = $ this ->timers [$ this ->profileToken ($ type , $ name , $ count )] ?? null ;
68+
69+ if ($ start === null ) {
70+ Log::debug ('profile end without start ' , [
71+ 'name ' => $ name ,
72+ 'type ' => $ type ,
73+ 'count ' => $ count ,
74+ ]);
75+
76+ return ;
77+ }
78+
79+ $ durationMs = round ((hrtime (true ) - $ start ) / 1_000_000 , 2 );
80+
81+ Log::debug ('profile end ' , [
82+ 'name ' => $ name ,
83+ 'type ' => $ type ,
84+ 'count ' => $ count ,
85+ 'duration_ms ' => $ durationMs ,
86+ ]);
5287 }
5388
5489 private function shouldProfile (): bool
@@ -67,7 +102,7 @@ private function shouldProfile(): bool
67102 return $ this ->shouldProfile = false ;
68103 }
69104
70- return $ this ->shouldProfile = $ user ->admin && $ user ->getPreference ('profileTemplates ' );
105+ return $ this ->shouldProfile = ( $ user ->admin && $ user ->getPreference ('profileTemplates ' ) );
71106 }
72107
73108 private function profileToken (string $ type , string $ name , int $ count ): string
0 commit comments