25
25
* @since 1.8.0
26
26
*/
27
27
function perflab_register_default_server_timing_before_template_metrics (): void {
28
- $ calculate_before_template_metrics = static function (): void {
28
+ $ current_function = __FUNCTION__ ;
29
+
30
+ $ calculate_before_template_metrics = static function () use ( $ current_function ): void {
29
31
// WordPress execution prior to serving the template.
30
32
perflab_server_timing_register_metric (
31
33
'before-template ' ,
@@ -44,17 +46,41 @@ function perflab_register_default_server_timing_before_template_metrics(): void
44
46
perflab_server_timing_register_metric (
45
47
'before-template-db-queries ' ,
46
48
array (
47
- 'measure_callback ' => static function ( $ metric ): void {
49
+ 'measure_callback ' => static function ( $ metric ) use ( $ current_function ) : void {
48
50
// This should never happen, but some odd database implementations may be doing it wrong.
49
51
if ( ! isset ( $ GLOBALS ['wpdb ' ]->queries ) || ! is_array ( $ GLOBALS ['wpdb ' ]->queries ) ) {
50
52
return ;
51
53
}
52
54
55
+ /**
56
+ * Query times.
57
+ *
58
+ * @var float[] $query_times
59
+ */
60
+ $ query_times = array ();
61
+ foreach ( $ GLOBALS ['wpdb ' ]->queries as $ query ) {
62
+ if ( ! is_array ( $ query ) || ! isset ( $ query [1 ] ) || ! is_float ( $ query [1 ] ) ) {
63
+ wp_trigger_error (
64
+ $ current_function ,
65
+ esc_html (
66
+ sprintf (
67
+ /* translators: 1: before-template-db-queries, 2: $wpdb->queries */
68
+ __ ( 'Unable to compute server timing for "%1$s" because a saved query in %2$s lacks the elapsed time as the second array value. ' , 'performance-lab ' ),
69
+ 'before-template-db-queries ' ,
70
+ '$wpdb->queries '
71
+ )
72
+ )
73
+ );
74
+ return ;
75
+ }
76
+ $ query_times [] = $ query [1 ];
77
+ }
78
+
53
79
// Store this value in a global to later subtract it from total query time after template.
54
80
$ GLOBALS ['perflab_query_time_before_template ' ] = array_reduce (
55
- $ GLOBALS [ ' wpdb ' ]-> queries ,
56
- static function ( $ acc , $ query ) {
57
- return $ acc + $ query [ 1 ] ;
81
+ $ query_times ,
82
+ static function ( float $ acc , float $ query_time ): float {
83
+ return $ acc + $ query_time ;
58
84
},
59
85
0.0
60
86
);
0 commit comments