-
Notifications
You must be signed in to change notification settings - Fork 4
/
PrometheusEncoder.php
71 lines (61 loc) · 1.66 KB
/
PrometheusEncoder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace PNX\Prometheus\Serializer;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
/**
* Provides and encoder for Prometheus text format.
*/
class PrometheusEncoder implements EncoderInterface {
const ENCODING = 'prometheus';
/**
* {@inheritdoc}
*/
public function supportsEncoding($format): bool {
return $format == self::ENCODING;
}
/**
* {@inheritdoc}
*/
public function encode($data, $format, array $context = []): string {
$output = [];
$output[] = '# HELP ' . $data['name'] . ' ' . $data['help'];
$output[] = '# TYPE ' . $data['name'] . ' ' . $data['type'];
foreach ($data['labelled_values'] as $labelledValue) {
$output[] = $labelledValue['name'] . $this->encodeLabels($labelledValue['labels']) . ' ' . $this->escapeValue($labelledValue['value']);
}
return implode("\n", $output) . "\n";
}
/**
* Encode the labels as in the prometheus format.
*
* @param array $labels
* The labels.
*
* @return string
* The labels in prometheus format.
*/
protected function encodeLabels(array $labels) {
if (empty($labels)) {
return '';
}
$output = [];
foreach ($labels as $key => $value) {
$output[] = $key . '="' . $value . '"';
}
return '{' . implode(',', $output) . '}';
}
/**
* Escape special characters in values.
*
* @param string $value
* The raw value.
*
* @return string
* The escaped value.
*/
protected function escapeValue($value) {
$value = str_replace("\"", "\\\"", $value);
$value = str_replace("\n", "\\n", $value);
$value = str_replace("\\", "\\\\", $value);
return $value;
}
}