<?php
class ApiMonitor {
private $endpoints = [];
private $dryRun = true; // Enable dry-run mode by default
public function __construct(array $endpoints) {
$this->endpoints = $endpoints;
}
public function setDryRun(bool $dryRun): void {
$this->dryRun = $dryRun;
}
public function monitorEndpoints(): void {
foreach ($this->endpoints as $endpoint) {
$this->checkEndpoint($endpoint);
}
}
private function checkEndpoint(array $endpoint): void {
$url = $endpoint['url'];
$method = $endpoint['method'] ?? 'GET'; // Default to GET if method is not specified
$expectedStatusCode = $endpoint['statusCode'];
$interval = $endpoint['interval'] ?? 60; // Default interval is 60 seconds
while (true) {
$startTime = time();
$response = $this->makeApiCall($url, $method);
$endTime = time();
$executionTime = $endTime - $startTime;
if ($this->dryRun) {
echo "DRY RUN: Checking $url ($method) - Status Code: " . $response['statusCode'] . ", Execution Time: " . $executionTime . "s\n";
} else {
if ($response['statusCode'] == $expectedStatusCode) {
echo "OK: $url ($method) - Status Code: " . $response['statusCode'] . ", Execution Time: " . $executionTime . "s\n";
} else {
echo "ERROR: $url ($method) - Status Code: " . $response['statusCode'] . ", Expected: " . $expectedStatusCode . ", Execution Time: " . $executionTime . "s\n";
}
}
sleep($interval);
}
}
private function makeApiCall(string $url, string $method): array {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json', // Example header
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
// Add data here if needed
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
throw new Exception("cURL error: " . $curlError);
}
return ['statusCode' => $httpCode, 'response' => $response];
}
}
Add your comment