1. <?php
  2. /**
  3. * Paginate HTTP response results with retry and fixed intervals.
  4. *
  5. * @param string $url The URL to fetch data from.
  6. * @param int $pageSize The number of results per page.
  7. * @param int $retryInterval The interval between retries in seconds.
  8. * @return array An array containing the paginated results, total count, and URL.
  9. * Returns an empty array on error.
  10. */
  11. function paginateHttp(string $url, int $pageSize, int $retryInterval): array
  12. {
  13. $allResults = [];
  14. $currentPage = 1;
  15. $totalCount = 0;
  16. do {
  17. try {
  18. $response = file_get_contents($url); // Fetch the data
  19. if ($response === false) {
  20. error_log("Error fetching URL: $url");
  21. return []; // Return empty array on failure
  22. }
  23. $data = json_decode($response, true); // Decode JSON
  24. if ($data === null) {
  25. error_log("Error decoding JSON from URL: $url");
  26. return []; // Return empty array on failure
  27. }
  28. $results = $data['results'] ?? []; // Assuming 'results' key contains the items
  29. $totalCount = count($results);
  30. $allResults = array_merge($allResults, $results);
  31. if (empty($results)) {
  32. break; // No more results
  33. }
  34. $url = $data['next'] ?? null; // Assuming 'next' key contains the URL for the next page
  35. if ($url === null) {
  36. break; // No next page
  37. }
  38. $currentPage++;
  39. usleep($retryInterval * 1000000); // Wait before retrying
  40. } catch (Exception $e) {
  41. error_log("Error during pagination: " . $e->getMessage());
  42. return []; // Return empty array on error
  43. }
  44. } while ($url !== null);
  45. $totalPages = ceil($totalCount / $pageSize);
  46. return [
  47. 'results' => array_slice($allResults, ($currentPage - 1) * $pageSize, $pageSize),
  48. 'totalCount' => $totalCount,
  49. 'pageSize' => $pageSize,
  50. 'totalPages' => $totalPages,
  51. 'url' => $url
  52. ];
  53. }
  54. ?>

Add your comment