Skip to content

Commit

Permalink
Backport WordPress/wordpress-develop#2625 to Gutenberg.
Browse files Browse the repository at this point in the history
  • Loading branch information
anton-vlasenko committed May 5, 2022
1 parent 6788546 commit c1b3456
Showing 1 changed file with 37 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,26 +57,16 @@ public function get_items( $request ) {
$query_args['slug'] = $slug;
}

/**
* Include a hash of the query args, so that different requests are stored in
* separate caches.
*
* MD5 is chosen for its speed, low-collision rate, universal availability, and to stay
* under the character limit for `_site_transient_timeout_{...}` keys.
*
* @link https://stackoverflow.com/questions/3665247/fastest-hash-for-non-cryptographic-uses
*/
$transient_key = 'wp_remote_block_patterns_' . md5( implode( '-', $query_args ) );
$transient_key = $this->get_transient_key( $query_args );

/**
/*
* Use network-wide transient to improve performance. The locale is the only site
* configuration that affects the response, and it's included in the transient key.
*/
$raw_patterns = get_site_transient( $transient_key );

if ( ! $raw_patterns ) {
$api_url = 'http://api.wordpress.org/patterns/1.0/?' . build_query( $query_args );

if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
Expand Down Expand Up @@ -135,4 +125,39 @@ public function get_items( $request ) {

return new WP_REST_Response( $response );
}

/*
* Include a hash of the query args, so that different requests are stored in
* separate caches.
*
* MD5 is chosen for its speed, low-collision rate, universal availability, and to stay
* under the character limit for `_site_transient_timeout_{...}` keys.
*
* @link https://stackoverflow.com/questions/3665247/fastest-hash-for-non-cryptographic-uses
*
* @since 6.0.0
*
* @param array $query_args Query arguments to generate a transient key from.
* @return string Transient key.
*/
protected function get_transient_key( $query_args ) {
if ( method_exists( get_parent_class( $this ), __FUNCTION__ ) ) {
return parent::get_transient_key( $query_args );
}

if ( isset( $query_args['slug'] ) ) {
// This is an additional precaution because the "sort" function expects an array.
$query_args['slug'] = wp_parse_list( $query_args['slug'] );

// Empty arrays should not affect the transient key.
if ( empty( $query_args['slug'] ) ) {
unset( $query_args['slug'] );
} else {
// Sort the array so that the transient key doesn't depend on the order of slugs.
sort( $query_args['slug'] );
}
}

return 'wp_remote_block_patterns_' . md5( serialize( $query_args ) );
}
}

0 comments on commit c1b3456

Please sign in to comment.