<?php
/**
* Mirrors data from API endpoints with retry logic for hypothesis validation.
*
* @param array $endpoints An array of API endpoint details. Each element
* should be an associative array with 'url', 'method',
* 'data' (optional), and 'retries' (number of retries).
* @param string $outputFile The file to write the mirrored data to.
* @return bool True on success, false on failure.
*/
function mirrorApiEndpoints(array $endpoints, string $outputFile): bool
{
$successful = true; // Track overall success
foreach ($endpoints as $endpoint) {
$url = $endpoint['url'];
$method = $endpoint['method'] ?? 'GET'; // Default to GET if not specified
$data = $endpoint['data'] ?? null;
$retries = $endpoint['retries'] ?? 3; // Default to 3 retries
$data_sent = [];
if ($data !== null) {
$data_sent = json_encode($data);
}
$success = false;
for ($i = 0; $i < $retries; $i++) {
try {
$response = apiRequest($url, $method, $data_sent);
if ($response && $response->http_code == 200) {
$data_to_write = json_decode($response->body, true); // Decode JSON
file_put_contents($outputFile, json_encode($data_to_write, JSON_PRETTY_PRINT) . "\n", FILE_APPEND);
$success = true;
break; // Exit retry loop on success
} else {
error_log("API request failed for $url (attempt $i+1): HTTP code " . $response ? $response->http_code : 'Unknown');
}
} catch (Exception $e) {
error_log("API request failed for $url (attempt $i+1): " . $e->getMessage());
}
}
if (!$success) {
$successful = false;
error_log("Failed to mirror data from $url after $retries attempts.");
}
}
return $successful;
}
/**
* Performs an API request with retry logic.
*
* @param string $url The API endpoint URL.
* @param string $method The HTTP method (GET, POST, PUT, DELETE, etc.).
* @param string $data The request body (optional).
* @return object|null The API response object, or null on failure.
* @throws Exception If an unexpected error occurs.
*/
function apiRequest(string $url, string $method, string $data = null): ?object
{
$options = [
'http' => [
'method' => $method,
'header' => "Content-type: application/json; charset=UTF-8",
'content' => $data ? $data : '',
'timeout' => 10 //seconds
],
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception("API request failed: " . error_get_last()['message']);
}
$response_obj = json_decode($response, true); // Decode JSON
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("JSON decoding error: " . json_last_error_msg());
}
return $response_obj;
}
// Example Usage (replace with your actual endpoints and output file)
$endpoints = [
[
'url' => 'https://jsonplaceholder.typicode.com/todos/1',
'method' => 'GET',
'retries' => 5,
],
[
'url' => 'https://jsonplaceholder.typicode.com/posts',
'method' => 'GET',
'data' => ['title' => 'My New Post', 'body' => 'This is the content of my post.'],
'retries' => 3,
],
];
$outputFile = 'mirrored_data.json';
if (mirrorApiEndpoints($endpoints, $output
Add your comment