-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetricEvent.php
More file actions
67 lines (60 loc) · 2.12 KB
/
MetricEvent.php
File metadata and controls
67 lines (60 loc) · 2.12 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
63
64
65
66
67
<?php
declare(strict_types=1);
namespace Arcp\Messages\Telemetry;
use Arcp\Envelope\MessageType;
use Arcp\Errors\InvalidArgumentException;
/** RFC §17.3 — telemetry sample. */
final readonly class MetricEvent extends MessageType
{
/** @param array<string, bool|float|int|string> $dims */
public function __construct(
public string $name,
public int|float $value,
public string $unit,
public array $dims = [],
) {
if ($name === '' || $unit === '') {
throw new InvalidArgumentException('metric name/unit missing');
}
}
#[\Override]
public static function typeName(): string
{
return 'metric';
}
#[\Override]
public function toArray(): array
{
$out = ['name' => $this->name, 'value' => $this->value, 'unit' => $this->unit];
if ($this->dims !== []) {
$out['dims'] = $this->dims;
}
return $out;
}
#[\Override]
public static function fromArray(array $data): static
{
$name = $data['name'] ?? throw new InvalidArgumentException('name missing');
$value = $data['value'] ?? throw new InvalidArgumentException('value missing');
$unit = $data['unit'] ?? throw new InvalidArgumentException('unit missing');
if (!\is_string($name) || !\is_string($unit)) {
throw new InvalidArgumentException('name/unit must be strings');
}
if (!\is_int($value) && !\is_float($value)) {
throw new InvalidArgumentException('value must be numeric');
}
$dims = [];
if (isset($data['dims'])) {
if (!\is_array($data['dims'])) {
throw new InvalidArgumentException('dims must be object');
}
foreach ($data['dims'] as $k => $v) {
if (!\is_string($k) || (!\is_string($v) && !\is_int($v) && !\is_float($v) && !\is_bool($v))) {
throw new InvalidArgumentException('dims entries must be string→scalar');
}
$dims[$k] = $v;
}
}
return new static($name, $value, $unit, $dims);
}
}