REST API: Reuse previously-generated embedded objects when building collection response.

Store each generated embedded object in a temporary cache when querying for linked resources so that repeated links to the same resource do not trigger repeated queries or processing.

Props TimothyBlynJacobs.
Fixes #48838.


Built from https://develop.svn.wordpress.org/trunk@47138


git-svn-id: http://core.svn.wordpress.org/trunk@46938 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
K. Adam White 2020-01-30 20:22:07 +00:00
parent d80131190f
commit b78819c3fa
2 changed files with 31 additions and 17 deletions

View File

@ -78,6 +78,14 @@ class WP_REST_Server {
*/ */
protected $route_options = array(); protected $route_options = array();
/**
* Caches embedded requests.
*
* @since 5.4.0
* @var array
*/
protected $embed_cache = array();
/** /**
* Instantiates the REST server. * Instantiates the REST server.
* *
@ -462,12 +470,14 @@ class WP_REST_Server {
} }
if ( $embed ) { if ( $embed ) {
$this->embed_cache = array();
// Determine if this is a numeric array. // Determine if this is a numeric array.
if ( wp_is_numeric_array( $data ) ) { if ( wp_is_numeric_array( $data ) ) {
$data = array_map( array( $this, 'embed_links' ), $data ); $data = array_map( array( $this, 'embed_links' ), $data );
} else { } else {
$data = $this->embed_links( $data ); $data = $this->embed_links( $data );
} }
$this->embed_cache = array();
} }
return $data; return $data;
@ -588,6 +598,7 @@ class WP_REST_Server {
continue; continue;
} }
if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
// Run through our internal routing and serve. // Run through our internal routing and serve.
$request = WP_REST_Request::from_url( $item['href'] ); $request = WP_REST_Request::from_url( $item['href'] );
if ( ! $request ) { if ( ! $request ) {
@ -605,7 +616,10 @@ class WP_REST_Server {
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request ); $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
$embeds[] = $this->response_to_data( $response, false ); $this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
}
$embeds[] = $this->embed_cache[ $item['href'] ];
} }
// Determine if any real links were found. // Determine if any real links were found.

View File

@ -13,7 +13,7 @@
* *
* @global string $wp_version * @global string $wp_version
*/ */
$wp_version = '5.4-alpha-47136'; $wp_version = '5.4-alpha-47138';
/** /**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.