PluginProbe
DecaLog / 4.4.0
DecaLog v4.4.0
3.0.2 3.1.0 3.10.0 3.2.0 3.3.0 3.4.0 3.4.1 3.5.0 3.5.1 3.6.0 3.6.1 3.6.2 3.6.3 3.7.0 3.7.1 3.8.0 3.9.0 3.9.1 4.0.0 4.1.0 4.2.0 4.3.0 4.3.1 4.4.0 4.5.0 All 75 releases
decalog / includes / libraries / prometheus / RenderTextFormat.php

RenderTextFormat.php in DecaLog 4.4.0, at includes/libraries/prometheus/RenderTextFormat.php

79 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Prometheus;
6
7 class RenderTextFormat implements RendererInterface
8 {
9 const MIME_TYPE = 'text/plain; version=0.0.4';
10
11 /**
12 * @param MetricFamilySamples[] $metrics
13 * @return string
14 */
15 public function render(array $metrics): string
16 {
17 usort($metrics, function (MetricFamilySamples $a, MetricFamilySamples $b): int {
18 return strcmp($a->getName(), $b->getName());
19 });
20
21 $lines = [];
22 foreach ($metrics as $metric) {
23 $lines[] = "# HELP " . $metric->getName() . " {$metric->getHelp()}";
24 $lines[] = "# TYPE " . $metric->getName() . " {$metric->getType()}";
25 foreach ($metric->getSamples() as $sample) {
26 $lines[] = $this->renderSample($metric, $sample);
27 }
28 }
29 return implode("\n", $lines) . "\n";
30 }
31
32 /**
33 * @param MetricFamilySamples $metric
34 * @param Sample $sample
35 * @return string
36 */
37 private function renderSample(MetricFamilySamples $metric, Sample $sample): string
38 {
39 $labelNames = $metric->getLabelNames();
40 if ($metric->hasLabelNames() || $sample->hasLabelNames()) {
41 $escapedLabels = $this->escapeAllLabels($labelNames, $sample);
42 return $sample->getName() . '{' . implode(',', $escapedLabels) . '} ' . $sample->getValue();
43 }
44 return $sample->getName() . ' ' . $sample->getValue();
45 }
46
47 /**
48 * @param string $v
49 * @return string
50 */
51 private function escapeLabelValue(string $v): string
52 {
53 return str_replace(["\\", "\n", "\""], ["\\\\", "\\n", "\\\""], $v);
54 }
55
56 /**
57 * @param string[] $labelNames
58 * @param Sample $sample
59 *
60 * @return string[]
61 */
62 private function escapeAllLabels(array $labelNames, Sample $sample): array
63 {
64 $escapedLabels = [];
65
66 $labels = array_combine(array_merge($labelNames, $sample->getLabelNames()), $sample->getLabelValues());
67
68 if ($labels === false) {
69 return [];
70 }
71
72 foreach ($labels as $labelName => $labelValue) {
73 $escapedLabels[] = $labelName . '="' . $this->escapeLabelValue((string) $labelValue) . '"';
74 }
75
76 return $escapedLabels;
77 }
78 }
79