1. <?php
  2. class ApiMonitor {
  3. private $endpoints = [];
  4. private $dryRun = true; // Enable dry-run mode by default
  5. public function __construct(array $endpoints) {
  6. $this->endpoints = $endpoints;
  7. }
  8. public function setDryRun(bool $dryRun): void {
  9. $this->dryRun = $dryRun;
  10. }
  11. public function monitorEndpoints(): void {
  12. foreach ($this->endpoints as $endpoint) {
  13. $this->checkEndpoint($endpoint);
  14. }
  15. }
  16. private function checkEndpoint(array $endpoint): void {
  17. $url = $endpoint['url'];
  18. $method = $endpoint['method'] ?? 'GET'; // Default to GET if method is not specified
  19. $expectedStatusCode = $endpoint['statusCode'];
  20. $interval = $endpoint['interval'] ?? 60; // Default interval is 60 seconds
  21. while (true) {
  22. $startTime = time();
  23. $response = $this->makeApiCall($url, $method);
  24. $endTime = time();
  25. $executionTime = $endTime - $startTime;
  26. if ($this->dryRun) {
  27. echo "DRY RUN: Checking $url ($method) - Status Code: " . $response['statusCode'] . ", Execution Time: " . $executionTime . "s\n";
  28. } else {
  29. if ($response['statusCode'] == $expectedStatusCode) {
  30. echo "OK: $url ($method) - Status Code: " . $response['statusCode'] . ", Execution Time: " . $executionTime . "s\n";
  31. } else {
  32. echo "ERROR: $url ($method) - Status Code: " . $response['statusCode'] . ", Expected: " . $expectedStatusCode . ", Execution Time: " . $executionTime . "s\n";
  33. }
  34. }
  35. sleep($interval);
  36. }
  37. }
  38. private function makeApiCall(string $url, string $method): array {
  39. $ch = curl_init($url);
  40. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  41. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  42. 'Content-Type: application/json', // Example header
  43. ]);
  44. if ($method === 'POST') {
  45. curl_setopt($ch, CURLOPT_POST, 1);
  46. // Add data here if needed
  47. }
  48. $response = curl_exec($ch);
  49. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  50. $curlError = curl_error($ch);
  51. curl_close($ch);
  52. if ($curlError) {
  53. throw new Exception("cURL error: " . $curlError);
  54. }
  55. return ['statusCode' => $httpCode, 'response' => $response];
  56. }
  57. }

Add your comment