Headers.php
74 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\API\REST\V3\Support; |
| 4 | |
| 5 | use WP_REST_Request; |
| 6 | use WP_REST_Response; |
| 7 | |
| 8 | /** |
| 9 | * Helper class to manage pagination headers for REST API responses. |
| 10 | * |
| 11 | * @since 4.8.0 |
| 12 | */ |
| 13 | class Headers |
| 14 | { |
| 15 | /** |
| 16 | * Add pagination headers to a REST response. |
| 17 | * |
| 18 | * @since 4.8.0 |
| 19 | * |
| 20 | * @param WP_REST_Response $response The response object to add headers to |
| 21 | * @param WP_REST_Request $request The request object |
| 22 | * @param int $totalItems Total number of items |
| 23 | * @param int $perPage Number of items per page |
| 24 | * @param string $routeBase The route base for building pagination URLs |
| 25 | * |
| 26 | * @return WP_REST_Response The response with headers added |
| 27 | */ |
| 28 | public static function addPagination( |
| 29 | WP_REST_Response $response, |
| 30 | WP_REST_Request $request, |
| 31 | int $totalItems, |
| 32 | int $perPage, |
| 33 | string $routeBase |
| 34 | ): WP_REST_Response { |
| 35 | $page = $request->get_param('page'); |
| 36 | $totalPages = (int) ceil($totalItems / $perPage); |
| 37 | |
| 38 | // Add total headers |
| 39 | $response->header('X-WP-Total', $totalItems); |
| 40 | $response->header('X-WP-TotalPages', $totalPages); |
| 41 | |
| 42 | // Build base URL for pagination links |
| 43 | $base = add_query_arg( |
| 44 | map_deep($request->get_query_params(), function ($value) { |
| 45 | if (is_bool($value)) { |
| 46 | $value = $value ? 'true' : 'false'; |
| 47 | } |
| 48 | |
| 49 | return urlencode($value); |
| 50 | }), |
| 51 | rest_url($routeBase) |
| 52 | ); |
| 53 | |
| 54 | // Add prev link header |
| 55 | if ($page > 1) { |
| 56 | $prevPage = $page - 1; |
| 57 | |
| 58 | if ($prevPage > $totalPages) { |
| 59 | $prevPage = $totalPages; |
| 60 | } |
| 61 | |
| 62 | $response->link_header('prev', add_query_arg('page', $prevPage, $base)); |
| 63 | } |
| 64 | |
| 65 | // Add next link header |
| 66 | if ($totalPages > $page) { |
| 67 | $nextPage = $page + 1; |
| 68 | $response->link_header('next', add_query_arg('page', $nextPage, $base)); |
| 69 | } |
| 70 | |
| 71 | return $response; |
| 72 | } |
| 73 | } |
| 74 |