UptimeKumaMetrics.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. class UptimeKumaMetrics
  3. {
  4. protected string $raw;
  5. private array $monitors = [];
  6. public function __construct(string $raw)
  7. {
  8. $this->raw = $raw;
  9. }
  10. public function process(): self
  11. {
  12. $processed = explode(PHP_EOL, $this->raw);
  13. $monitors = array_filter($processed, function (string $item) {
  14. return str_starts_with($item, 'monitor_status');
  15. });
  16. // TODO: parse the latencies and add them on to the info card
  17. $latencies = array_filter($processed, function (string $item) {
  18. return str_starts_with($item, 'monitor_response_time');
  19. });
  20. $monitors = array_map(function (string $item) {
  21. return $this->parseMonitorStatus($item);
  22. }, $monitors);
  23. $this->addLatencyToMonitors($monitors, $latencies);
  24. $this->monitors = array_values(array_filter($monitors));
  25. return $this;
  26. }
  27. public function getMonitors(): array
  28. {
  29. return $this->monitors;
  30. }
  31. private function parseMonitorStatus(string $status): ?array
  32. {
  33. if (substr($status, -1) === '2') {
  34. return null;
  35. }
  36. $up = (substr($status, -1)) == '0' ? false : true;
  37. $status = substr($status, 15);
  38. $status = substr($status, 0, -4);
  39. $status = explode(',', $status);
  40. $data = [
  41. 'name' => $this->getStringBetweenQuotes($status[0]),
  42. 'url' => $this->getStringBetweenQuotes($status[2]),
  43. 'type' => $this->getStringBetweenQuotes($status[1]),
  44. 'status' => $up,
  45. ];
  46. return $data;
  47. }
  48. private function addLatencyToMonitors(array &$monitors, array $latencies)
  49. {
  50. $latencies = $this->getLatenciesByName($latencies);
  51. foreach ($monitors as &$monitor) {
  52. $monitor['latency'] = $latencies[$monitor['name']] ?? null;
  53. }
  54. }
  55. private function getLatenciesByName(array $latencies): array
  56. {
  57. $l = [];
  58. foreach ($latencies as $latency) {
  59. if (preg_match('/monitor_name="(.*)",monitor_type.* ([0-9]{1,})$/', $latency, $match)) {
  60. $l[$match[1]] = (int) $match[2];
  61. }
  62. continue;
  63. }
  64. return $l;
  65. }
  66. private function getStringBetweenQuotes(string $input): string
  67. {
  68. if (preg_match('/"(.*?)"/', $input, $match) == 1) {
  69. return $match[1];
  70. }
  71. return '';
  72. }
  73. }