Skip to content

Commit

Permalink
Device_Detection: get_info(): memoize (#39338)
Browse files Browse the repository at this point in the history
  • Loading branch information
mreishus authored Sep 11, 2024
1 parent 94a3510 commit a76a351
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: changed

Device_Detection::get_info() will now memoize its result
31 changes: 31 additions & 0 deletions projects/packages/device-detection/src/class-device-detection.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@
*/
class Device_Detection {

/**
* Memoization cache for get_info() results.
*
* @var array
*/
private static $get_info_memo = array();

/**
* Maximum size of the memoization cache.
*
* @var int
*/
private static $max_memo_size = 100;

/**
* Returns information about the current device accessing the page.
*
Expand All @@ -41,6 +55,16 @@ class Device_Detection {
* );
*/
public static function get_info( $ua = '' ) {
// Return memoized result if available.
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
$memo_key = ! empty( $ua ) ? $ua : ( $_SERVER['HTTP_USER_AGENT'] ?? '' );
// Note: UA string used raw for compatibility reasons.
// No sanitization is needed as the value is never output or persisted, and is only used for memoization.
// phpcs:enable WordPress.Security.ValidatedSanitizedInput
if ( isset( self::$get_info_memo[ $memo_key ] ) ) {
return self::$get_info_memo[ $memo_key ];
}

$ua_info = new User_Agent_Info( $ua );

$info = array(
Expand Down Expand Up @@ -68,6 +92,13 @@ public static function get_info( $ua = '' ) {
*/
$info = apply_filters( 'jetpack_device_detection_get_info', $info, $ua, $ua_info );
}

// Memoize the result.
self::$get_info_memo[ $memo_key ] = $info;
if ( count( self::$get_info_memo ) > self::$max_memo_size ) {
array_shift( self::$get_info_memo );
}

return $info;
}

Expand Down

0 comments on commit a76a351

Please sign in to comment.