1. <?php
  2. /**
  3. * Mirrors data from API endpoints with retry logic for hypothesis validation.
  4. *
  5. * @param array $endpoints An array of API endpoint details. Each element
  6. * should be an associative array with 'url', 'method',
  7. * 'data' (optional), and 'retries' (number of retries).
  8. * @param string $outputFile The file to write the mirrored data to.
  9. * @return bool True on success, false on failure.
  10. */
  11. function mirrorApiEndpoints(array $endpoints, string $outputFile): bool
  12. {
  13. $successful = true; // Track overall success
  14. foreach ($endpoints as $endpoint) {
  15. $url = $endpoint['url'];
  16. $method = $endpoint['method'] ?? 'GET'; // Default to GET if not specified
  17. $data = $endpoint['data'] ?? null;
  18. $retries = $endpoint['retries'] ?? 3; // Default to 3 retries
  19. $data_sent = [];
  20. if ($data !== null) {
  21. $data_sent = json_encode($data);
  22. }
  23. $success = false;
  24. for ($i = 0; $i < $retries; $i++) {
  25. try {
  26. $response = apiRequest($url, $method, $data_sent);
  27. if ($response && $response->http_code == 200) {
  28. $data_to_write = json_decode($response->body, true); // Decode JSON
  29. file_put_contents($outputFile, json_encode($data_to_write, JSON_PRETTY_PRINT) . "\n", FILE_APPEND);
  30. $success = true;
  31. break; // Exit retry loop on success
  32. } else {
  33. error_log("API request failed for $url (attempt $i+1): HTTP code " . $response ? $response->http_code : 'Unknown');
  34. }
  35. } catch (Exception $e) {
  36. error_log("API request failed for $url (attempt $i+1): " . $e->getMessage());
  37. }
  38. }
  39. if (!$success) {
  40. $successful = false;
  41. error_log("Failed to mirror data from $url after $retries attempts.");
  42. }
  43. }
  44. return $successful;
  45. }
  46. /**
  47. * Performs an API request with retry logic.
  48. *
  49. * @param string $url The API endpoint URL.
  50. * @param string $method The HTTP method (GET, POST, PUT, DELETE, etc.).
  51. * @param string $data The request body (optional).
  52. * @return object|null The API response object, or null on failure.
  53. * @throws Exception If an unexpected error occurs.
  54. */
  55. function apiRequest(string $url, string $method, string $data = null): ?object
  56. {
  57. $options = [
  58. 'http' => [
  59. 'method' => $method,
  60. 'header' => "Content-type: application/json; charset=UTF-8",
  61. 'content' => $data ? $data : '',
  62. 'timeout' => 10 //seconds
  63. ],
  64. ];
  65. $context = stream_context_create($options);
  66. $response = file_get_contents($url, false, $context);
  67. if ($response === false) {
  68. throw new Exception("API request failed: " . error_get_last()['message']);
  69. }
  70. $response_obj = json_decode($response, true); // Decode JSON
  71. if (json_last_error() !== JSON_ERROR_NONE) {
  72. throw new Exception("JSON decoding error: " . json_last_error_msg());
  73. }
  74. return $response_obj;
  75. }
  76. // Example Usage (replace with your actual endpoints and output file)
  77. $endpoints = [
  78. [
  79. 'url' => 'https://jsonplaceholder.typicode.com/todos/1',
  80. 'method' => 'GET',
  81. 'retries' => 5,
  82. ],
  83. [
  84. 'url' => 'https://jsonplaceholder.typicode.com/posts',
  85. 'method' => 'GET',
  86. 'data' => ['title' => 'My New Post', 'body' => 'This is the content of my post.'],
  87. 'retries' => 3,
  88. ],
  89. ];
  90. $outputFile = 'mirrored_data.json';
  91. if (mirrorApiEndpoints($endpoints, $output

Add your comment