REST API: Introduce WP_Post_Type::get_rest_controller() caching method to prevent unnecessary REST controller construction.

Cache REST controller references on their associated post type object to prevent unnecessary controller re-instantiation, which previously caused "rest_prepare_{$post_type}" and "rest_{$post_type}_query" to run twice per request.

Props TimothyBlynJacobs, patrelentlesstechnologycom.
Fixes #45677.


git-svn-id: https://develop.svn.wordpress.org/trunk@46272 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
K. Adam White
2019-09-23 20:24:59 +00:00
parent 509647e568
commit 49155e679c
7 changed files with 150 additions and 11 deletions
@@ -4526,6 +4526,87 @@ class WP_Test_REST_Posts_Controller extends WP_Test_REST_Post_Type_Controller_Te
$this->assertNotEquals( '0000-00-00 00:00:00', get_post( $post->ID )->post_date_gmt );
}
/**
* @ticket 45677
*/
public function test_get_for_post_type_reuses_same_instance() {
$this->assertSame(
get_post_type_object( 'post' )->get_rest_controller(),
get_post_type_object( 'post' )->get_rest_controller()
);
}
/**
* @ticket 45677
*/
public function test_get_for_post_type_returns_null_if_post_type_does_not_show_in_rest() {
register_post_type(
'not_in_rest',
array(
'show_in_rest' => false,
)
);
$this->assertNull( get_post_type_object( 'not_in_rest' )->get_rest_controller() );
}
/**
* @ticket 45677
*/
public function test_get_for_post_type_returns_null_if_class_does_not_exist() {
register_post_type(
'class_not_found',
array(
'show_in_rest' => true,
'rest_controller_class' => 'Class_That_Does_Not_Exist',
)
);
$this->assertNull( get_post_type_object( 'class_not_found' )->get_rest_controller() );
}
/**
* @ticket 45677
*/
public function test_get_for_post_type_returns_null_if_class_does_not_subclass_rest_controller() {
register_post_type(
'invalid_class',
array(
'show_in_rest' => true,
'rest_controller_class' => 'WP_Post',
)
);
$this->assertNull( get_post_type_object( 'invalid_class' )->get_rest_controller() );
}
/**
* @ticket 45677
*/
public function test_get_for_post_type_returns_posts_controller_if_custom_class_not_specified() {
register_post_type(
'test',
array(
'show_in_rest' => true,
)
);
$this->assertInstanceOf(
WP_REST_Posts_Controller::class,
get_post_type_object( 'test' )->get_rest_controller()
);
}
/**
* @ticket 45677
*/
public function test_get_for_post_type_returns_provided_controller_class() {
$this->assertInstanceOf(
WP_REST_Blocks_Controller::class,
get_post_type_object( 'wp_block' )->get_rest_controller()
);
}
public function tearDown() {
_unregister_post_type( 'private-post' );
_unregister_post_type( 'youseeme' );