<?php
class ApiMetrics {
private $metrics = [];
private $manualOverrides = [];
public function __construct() {
$this->metrics = [];
$this->manualOverrides = [];
}
/**
* Records API response metrics.
*
* @param string $endpoint The API endpoint.
* @param int $responseCode The HTTP response code.
* @param int $responseTimeMs Response time in milliseconds.
* @param string $bodySize Body size of the response in bytes.
* @param array $headers Response headers.
*/
public function recordResponse(string $endpoint, int $responseCode, int $responseTimeMs, int $bodySize, array $headers): void {
// Override manual values if set
if (isset($this->manualOverrides[$endpoint])) {
$this->metrics[$endpoint]['responseCode'] = $this->manualOverrides[$endpoint]['responseCode'];
$this->metrics[$endpoint]['responseTimeMs'] = $this->manualOverrides[$endpoint]['responseTimeMs'];
$this->metrics[$endpoint]['bodySize'] = $this->manualOverrides[$endpoint]['bodySize'];
$this->metrics[$endpoint]['headers'] = $this->manualOverrides[$endpoint]['headers'];
return;
}
$this->metrics[$endpoint] = [
'responseCode' => $responseCode,
'responseTimeMs' => $responseTimeMs,
'bodySize' => $bodySize,
'headers' => $headers,
];
}
/**
* Sets a manual override for metrics of a specific endpoint.
*
* @param string $endpoint The API endpoint.
* @param array $override An associative array of metrics to override.
*/
public function setManualOverride(string $endpoint, array $override): void {
$this->manualOverrides[$endpoint] = $override;
}
/**
* Gets the collected metrics for a specific endpoint.
*
* @param string $endpoint The API endpoint.
* @return array|null The metrics array, or null if not found.
*/
public function getMetrics(string $endpoint): ?array {
return isset($this->metrics[$endpoint]) ? $this->metrics[$endpoint] : null;
}
/**
* Gets all collected metrics.
*
* @return array All metrics collected.
*/
public function getAllMetrics(): array {
return $this->metrics;
}
/**
* Gets all manual overrides.
*
* @return array All manual overrides.
*/
public function getAllManualOverrides(): array {
return $this->manualOverrides;
}
}
?>
Add your comment