PaginationHeaders.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace Webkul\BagistoApi\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. /**
  7. * Reads pagination metadata stashed by PaginationHeaderNormalizer and
  8. * adds standard X-* headers to the outgoing response.
  9. *
  10. * X-Total-Count total number of items across all pages
  11. * X-Page current page (1-based)
  12. * X-Per-Page items per page
  13. * X-Total-Pages total number of pages
  14. *
  15. * Headers are added only when the normalizer captured a Paginator — i.e.
  16. * for paginated REST collection responses. Single-resource and non-paginated
  17. * collection responses are unchanged.
  18. */
  19. class PaginationHeaders
  20. {
  21. public function handle(Request $request, Closure $next): Response
  22. {
  23. $response = $next($request);
  24. $meta = $request->attributes->get('bagistoapi.pagination');
  25. if (is_array($meta)) {
  26. $response->headers->set('X-Total-Count', (string) $meta['total']);
  27. $response->headers->set('X-Page', (string) $meta['page']);
  28. $response->headers->set('X-Per-Page', (string) $meta['per_page']);
  29. $response->headers->set('X-Total-Pages', (string) $meta['total_pages']);
  30. }
  31. return $response;
  32. }
  33. }