1. <?php
  2. /**
  3. * Archives API responses with validation checks and defensive coding.
  4. *
  5. * @param string $apiUrl The API endpoint URL.
  6. * @param array $headers Optional HTTP headers.
  7. * @param array $data Optional data to send with the request.
  8. * @param string $archiveDir The directory to store the archived responses.
  9. * @return array|null An associative array containing the response data,
  10. * status code, and any errors. Returns null on failure.
  11. */
  12. function archiveApiData(string $apiUrl, array $headers = [], array $data = [], string $archiveDir = 'api_archives'): ?array
  13. {
  14. // Defensive check: Ensure the API URL is valid.
  15. if (empty($apiUrl)) {
  16. error_log("Error: API URL is empty.");
  17. return null;
  18. }
  19. // Ensure archive directory exists and is writable.
  20. if (!is_dir($archiveDir) || !is_writable($archiveDir)) {
  21. error_log("Error: Archive directory '$archiveDir' does not exist or is not writable.");
  22. return null;
  23. }
  24. try {
  25. // Make the API request.
  26. $response = file_get_contents($apiUrl);
  27. if ($response === false) {
  28. $error = "Error: Failed to fetch data from API '$apiUrl'.";
  29. error_log($error);
  30. return ['error' => $error];
  31. }
  32. // Validate the response.
  33. $statusCode = (int)substr($response, 0, 3); // Extract status code from the beginning of response
  34. if ($statusCode < 200 || $statusCode >= 300) {
  35. $error = "Error: API returned an invalid status code: $statusCode. Response: $response";
  36. error_log($error);
  37. return ['error' => $error];
  38. }
  39. // Archive the response.
  40. $timestamp = date('YmdHis');
  41. $archiveFilename = $archiveDir . '/' . $timestamp . '_' . basename($apiUrl);
  42. file_put_contents($archiveFilename, $response);
  43. error_log("API response archived to: $archiveFilename");
  44. // Decode the response (assuming JSON).
  45. $data = json_decode($response, true); // Decode to associative array
  46. if (json_last_error() !== JSON_ERROR_NONE) {
  47. $error = "Error: Failed to decode JSON response: " . json_last_error_msg();
  48. error_log($error);
  49. return ['error' => $error];
  50. }
  51. return ['data' => $data, 'statusCode' => $statusCode];
  52. } catch (Exception $e) {
  53. error_log("Exception: " . $e->getMessage());
  54. return ['error' => "An unexpected error occurred: " . $e->getMessage()];
  55. }
  56. }
  57. ?>

Add your comment