From d0ca8ef345f0b8519efe9fd8ce10574f37881969 Mon Sep 17 00:00:00 2001 From: saimonh3 Date: Fri, 28 Dec 2018 15:35:07 +0600 Subject: [PATCH] feat: add format_collection_response method --- includes/api/admin/class-admin-controller.php | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/includes/api/admin/class-admin-controller.php b/includes/api/admin/class-admin-controller.php index 765ec5b1e8..9fa5fed30f 100644 --- a/includes/api/admin/class-admin-controller.php +++ b/includes/api/admin/class-admin-controller.php @@ -27,4 +27,49 @@ public function check_permission() { return current_user_can( 'manage_options' ); } + /** + * Format item's collection for response + * + * @param object $response + * @param object $request + * @param array $items + * @param int $total_items + * + * @since 2.9.8 + * + * @return object + */ + public function format_collection_response( $response, $request, $total_items ) { + if ( $total_items === 0 ) { + return $response; + } + + // pagation values for headers + $per_page = (int) ( ! empty( $request['per_page'] ) ? $request['per_page'] : 20 ); + $page = (int) ( ! empty( $request['page'] ) ? $request['page'] : 1 ); + + $response->header( 'X-WP-Total', (int) $total_items ); + + $max_pages = ceil( $total_items / $per_page ); + + $response->header( 'X-WP-TotalPages', (int) $max_pages ); + $base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->base ) ) ); + + if ( $page > 1 ) { + $prev_page = $page - 1; + if ( $prev_page > $max_pages ) { + $prev_page = $max_pages; + } + $prev_link = add_query_arg( 'page', $prev_page, $base ); + $response->link_header( 'prev', $prev_link ); + } + if ( $max_pages > $page ) { + + $next_page = $page + 1; + $next_link = add_query_arg( 'page', $next_page, $base ); + $response->link_header( 'next', $next_link ); + } + + return $response; + } }