| 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 |
|