Skip to content

Commit 99248a4

Browse files
committed
Add type checking for expected elapsed time in saved queries
1 parent 01a0027 commit 99248a4

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

plugins/performance-lab/includes/server-timing/defaults.php

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@
2525
* @since 1.8.0
2626
*/
2727
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 {
2931
// WordPress execution prior to serving the template.
3032
perflab_server_timing_register_metric(
3133
'before-template',
@@ -44,17 +46,41 @@ function perflab_register_default_server_timing_before_template_metrics(): void
4446
perflab_server_timing_register_metric(
4547
'before-template-db-queries',
4648
array(
47-
'measure_callback' => static function ( $metric ): void {
49+
'measure_callback' => static function ( $metric ) use ( $current_function ): void {
4850
// This should never happen, but some odd database implementations may be doing it wrong.
4951
if ( ! isset( $GLOBALS['wpdb']->queries ) || ! is_array( $GLOBALS['wpdb']->queries ) ) {
5052
return;
5153
}
5254

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+
5379
// Store this value in a global to later subtract it from total query time after template.
5480
$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;
5884
},
5985
0.0
6086
);

0 commit comments

Comments
 (0)