REST API: Add filters to allow creating REST API middleware plugins.

Introduce two new filters: `rest_request_before_callbacks` and `rest_request_after_callbacks` to
assist REST API middleware plugins to perform pre-callback and cleanup hooks such as `switch_to_blog()`
or caching implementations.

Props jnylen0.
Fixes #35590.


git-svn-id: https://develop.svn.wordpress.org/trunk@38689 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Joe Hoyle 2016-09-30 20:11:10 +00:00
parent 8c3dd28ec7
commit 4c6d7c8498
1 changed files with 40 additions and 0 deletions

View File

@ -874,6 +874,24 @@ class WP_REST_Server {
}
}
/**
* Call a filter before executing any REST API callbacks.
*
* Allows plugins to perform additional validation after a
* request is initialized and matched to a registered route,
* but before it is executed.
*
* Note that this filter will not be called for requests that
* fail to authenticate or match to a registered route.
*
* @since 4.7.0
*
* @param WP_HTTP_Response $response Result to send to the client. Usually a WP_REST_Response.
* @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
* @param WP_REST_Request $request Request used to generate the response.
*/
$response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
if ( ! is_wp_error( $response ) ) {
// Check permission specified on the route.
if ( ! empty( $handler['permission_callback'] ) ) {
@ -911,6 +929,28 @@ class WP_REST_Server {
}
}
/**
* Call a filter immediately after executing any REST API
* callbacks.
*
* Allows plugins to perform any needed cleanup, for example,
* to undo changes made during `rest_request_before_callbacks`.
*
* Note that this filter will not be called for requests that
* fail to authenticate or match to a registered route.
*
* Note that an endpoint's `permission_callback` can still be
* called after this filter - see the `rest_send_allow_header`
* function.
*
* @since 4.7.0
*
* @param WP_HTTP_Response $response Result to send to the client. Usually a WP_REST_Response.
* @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
* @param WP_REST_Request $request Request used to generate the response.
*/
$response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
if ( is_wp_error( $response ) ) {
$response = $this->error_to_response( $response );
} else {