1. <?php
  2. class ApiMetrics {
  3. private $metrics = [];
  4. private $manualOverrides = [];
  5. public function __construct() {
  6. $this->metrics = [];
  7. $this->manualOverrides = [];
  8. }
  9. /**
  10. * Records API response metrics.
  11. *
  12. * @param string $endpoint The API endpoint.
  13. * @param int $responseCode The HTTP response code.
  14. * @param int $responseTimeMs Response time in milliseconds.
  15. * @param string $bodySize Body size of the response in bytes.
  16. * @param array $headers Response headers.
  17. */
  18. public function recordResponse(string $endpoint, int $responseCode, int $responseTimeMs, int $bodySize, array $headers): void {
  19. // Override manual values if set
  20. if (isset($this->manualOverrides[$endpoint])) {
  21. $this->metrics[$endpoint]['responseCode'] = $this->manualOverrides[$endpoint]['responseCode'];
  22. $this->metrics[$endpoint]['responseTimeMs'] = $this->manualOverrides[$endpoint]['responseTimeMs'];
  23. $this->metrics[$endpoint]['bodySize'] = $this->manualOverrides[$endpoint]['bodySize'];
  24. $this->metrics[$endpoint]['headers'] = $this->manualOverrides[$endpoint]['headers'];
  25. return;
  26. }
  27. $this->metrics[$endpoint] = [
  28. 'responseCode' => $responseCode,
  29. 'responseTimeMs' => $responseTimeMs,
  30. 'bodySize' => $bodySize,
  31. 'headers' => $headers,
  32. ];
  33. }
  34. /**
  35. * Sets a manual override for metrics of a specific endpoint.
  36. *
  37. * @param string $endpoint The API endpoint.
  38. * @param array $override An associative array of metrics to override.
  39. */
  40. public function setManualOverride(string $endpoint, array $override): void {
  41. $this->manualOverrides[$endpoint] = $override;
  42. }
  43. /**
  44. * Gets the collected metrics for a specific endpoint.
  45. *
  46. * @param string $endpoint The API endpoint.
  47. * @return array|null The metrics array, or null if not found.
  48. */
  49. public function getMetrics(string $endpoint): ?array {
  50. return isset($this->metrics[$endpoint]) ? $this->metrics[$endpoint] : null;
  51. }
  52. /**
  53. * Gets all collected metrics.
  54. *
  55. * @return array All metrics collected.
  56. */
  57. public function getAllMetrics(): array {
  58. return $this->metrics;
  59. }
  60. /**
  61. * Gets all manual overrides.
  62. *
  63. * @return array All manual overrides.
  64. */
  65. public function getAllManualOverrides(): array {
  66. return $this->manualOverrides;
  67. }
  68. }
  69. ?>

Add your comment