-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJsonSerializer.php
More file actions
62 lines (49 loc) · 1.97 KB
/
JsonSerializer.php
File metadata and controls
62 lines (49 loc) · 1.97 KB
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
<?php
declare(strict_types=1);
namespace Zlodes\PrometheusClient\KeySerialization;
use InvalidArgumentException;
use JsonException;
use Webmozart\Assert\Assert;
use Zlodes\PrometheusClient\Exception\MetricKeySerializationException;
use Zlodes\PrometheusClient\Exception\MetricKeyUnserializationException;
use Zlodes\PrometheusClient\Storage\DTO\MetricNameWithLabels;
final class JsonSerializer implements Serializer
{
public function serialize(MetricNameWithLabels $metricNameWithLabels): string
{
$name = $metricNameWithLabels->metricName;
$labels = $metricNameWithLabels->labels;
if ($labels === []) {
return $name;
}
ksort($labels);
try {
$labelsString = json_encode($labels, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new MetricKeySerializationException("JSON encoding error", previous: $e);
}
return $name . '|' . $labelsString;
}
public function unserialize(string $key): MetricNameWithLabels
{
try {
$nameWithLabelsRaw = explode('|', $key, 2);
Assert::notEmpty($nameWithLabelsRaw);
Assert::countBetween($nameWithLabelsRaw, 1, 2);
$name = $nameWithLabelsRaw[0];
Assert::notEmpty($name);
$labels = array_key_exists(1, $nameWithLabelsRaw)
? json_decode($nameWithLabelsRaw[1], true, 2, JSON_THROW_ON_ERROR)
: [];
Assert::isArray($labels);
Assert::allStringNotEmpty($labels, 'Labels keys and values must be non-empty strings');
/** @psalm-var array<non-empty-string, non-empty-string> $labels */
return new MetricNameWithLabels($name, $labels);
} catch (JsonException | InvalidArgumentException $e) {
throw new MetricKeyUnserializationException(
"Cannot unserialize metrics key: {$e->getMessage()}",
previous: $e
);
}
}
}