UptimeKumaMetrics.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. if (preg_match('/{(.*?)}/', $status, $match) != 1) {
  37. return null;
  38. }
  39. $matches = explode(',', $match[1]);
  40. $data = [];
  41. foreach ($matches as $match) {
  42. switch (true) {
  43. case str_starts_with($match, "monitor_name"):
  44. $data['name'] = $this->getStringBetweenQuotes($match);
  45. break;
  46. case str_starts_with($match, "monitor_url"):
  47. $data['url'] = $this->getStringBetweenQuotes($match);
  48. break;
  49. case str_starts_with($match, "monitor_type"):
  50. $data['type'] = $this->getStringBetweenQuotes($match);
  51. break;
  52. }
  53. }
  54. $up = (substr($status, -1)) == '0' ? false : true;
  55. $data['status'] = $up;
  56. return $data;
  57. }
  58. private function addLatencyToMonitors(array &$monitors, array $latencies)
  59. {
  60. $latencies = $this->getLatenciesByName($latencies);
  61. foreach ($monitors as &$monitor) {
  62. $monitor['latency'] = $latencies[$monitor['name']] ?? null;
  63. }
  64. }
  65. private function getLatenciesByName(array $latencies): array
  66. {
  67. $l = [];
  68. foreach ($latencies as $latency) {
  69. if (preg_match('/monitor_name="(.*)",monitor_type.* ([0-9]{1,})$/', $latency, $match)) {
  70. $l[$match[1]] = (int) $match[2];
  71. }
  72. continue;
  73. }
  74. return $l;
  75. }
  76. private function getStringBetweenQuotes(string $input): string
  77. {
  78. if (preg_match('/"(.*?)"/', $input, $match) == 1) {
  79. return $match[1];
  80. }
  81. return '';
  82. }
  83. }