1. <?php
  2. /**
  3. * Loads response headers for backward compatibility with retry logic.
  4. *
  5. * This function retrieves specific response headers (e.g., 'Retry-After', 'Cache-Control')
  6. * and parses them to provide information useful for retry attempts. It offers
  7. * backward compatibility by handling cases where certain headers might be missing.
  8. *
  9. * @param Psr7\ClientInterface|null $client The HTTP client. Defaults to null (using default client).
  10. * @return array An associative array of response headers. Returns an empty array on failure.
  11. */
  12. function getRetryHeaders(Psr7\ClientInterface|null $client = null): array
  13. {
  14. $headers = [];
  15. if ($client === null) {
  16. // Use default client if not provided.
  17. $client = $this->getClient(); // Assuming getClient() is defined elsewhere and returns a Psr7\ClientInterface
  18. }
  19. try {
  20. $response = $client->get('/'); // Replace '/' with the actual URL.
  21. $headers = $response->getHeaders();
  22. } catch (\Exception $e) {
  23. // Handle exceptions during request. Return empty array on error.
  24. error_log("Error getting response headers: " . $e->getMessage());
  25. return [];
  26. }
  27. // Extract Retry-After header.
  28. $retryAfter = $headers['Retry-After'] ?? null;
  29. if ($retryAfter !== null && is_numeric($retryAfter)) {
  30. $headers['retry_after'] = (int)$retryAfter; // Cast to integer
  31. }
  32. // Extract Cache-Control header.
  33. $cacheControl = $headers['Cache-Control'] ?? '';
  34. if (!empty($cacheControl)) {
  35. //Further parsing of Cache-Control might be needed, but example is just to get the value.
  36. $headers['cache_control'] = $cacheControl;
  37. }
  38. // Extract other relevant headers (e.g., Max-Retry) - Add more headers as needed.
  39. $maxRetry = $headers['Max-Retry'] ?? null;
  40. if ($maxRetry !== null && is_numeric($maxRetry)) {
  41. $headers['max_retry'] = (int)$maxRetry;
  42. }
  43. return $headers;
  44. }
  45. /**
  46. * Placeholder for getting the client. Must be defined elsewhere.
  47. * @return Psr7\ClientInterface
  48. */
  49. function getClient(): Psr7\ClientInterface
  50. {
  51. // Replace with your actual client retrieval logic.
  52. // This is just a placeholder.
  53. return new \GuzzleHttp\Client();
  54. }
  55. ?>

Add your comment