From 4c6d7c8498e87ba690764d29da8526b5825c4247 Mon Sep 17 00:00:00 2001 From: Joe Hoyle Date: Fri, 30 Sep 2016 20:11:10 +0000 Subject: [PATCH] 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 --- .../rest-api/class-wp-rest-server.php | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/wp-includes/rest-api/class-wp-rest-server.php b/src/wp-includes/rest-api/class-wp-rest-server.php index 1e5914bfe7..0a763183a9 100644 --- a/src/wp-includes/rest-api/class-wp-rest-server.php +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -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 {