<?php
/**
* Archives API responses with validation checks and defensive coding.
*
* @param string $apiUrl The API endpoint URL.
* @param array $headers Optional HTTP headers.
* @param array $data Optional data to send with the request.
* @param string $archiveDir The directory to store the archived responses.
* @return array|null An associative array containing the response data,
* status code, and any errors. Returns null on failure.
*/
function archiveApiData(string $apiUrl, array $headers = [], array $data = [], string $archiveDir = 'api_archives'): ?array
{
// Defensive check: Ensure the API URL is valid.
if (empty($apiUrl)) {
error_log("Error: API URL is empty.");
return null;
}
// Ensure archive directory exists and is writable.
if (!is_dir($archiveDir) || !is_writable($archiveDir)) {
error_log("Error: Archive directory '$archiveDir' does not exist or is not writable.");
return null;
}
try {
// Make the API request.
$response = file_get_contents($apiUrl);
if ($response === false) {
$error = "Error: Failed to fetch data from API '$apiUrl'.";
error_log($error);
return ['error' => $error];
}
// Validate the response.
$statusCode = (int)substr($response, 0, 3); // Extract status code from the beginning of response
if ($statusCode < 200 || $statusCode >= 300) {
$error = "Error: API returned an invalid status code: $statusCode. Response: $response";
error_log($error);
return ['error' => $error];
}
// Archive the response.
$timestamp = date('YmdHis');
$archiveFilename = $archiveDir . '/' . $timestamp . '_' . basename($apiUrl);
file_put_contents($archiveFilename, $response);
error_log("API response archived to: $archiveFilename");
// Decode the response (assuming JSON).
$data = json_decode($response, true); // Decode to associative array
if (json_last_error() !== JSON_ERROR_NONE) {
$error = "Error: Failed to decode JSON response: " . json_last_error_msg();
error_log($error);
return ['error' => $error];
}
return ['data' => $data, 'statusCode' => $statusCode];
} catch (Exception $e) {
error_log("Exception: " . $e->getMessage());
return ['error' => "An unexpected error occurred: " . $e->getMessage()];
}
}
?>
Add your comment