1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Krenor\Prometheus\Metrics; |
4
|
|
|
|
5
|
|
|
use Krenor\Prometheus\Contracts\Storage; |
6
|
|
|
use Tightenco\Collect\Support\Collection; |
7
|
|
|
use Krenor\Prometheus\Exceptions\LabelException; |
8
|
|
|
use Krenor\Prometheus\Exceptions\PrometheusException; |
9
|
|
|
use Krenor\Prometheus\Contracts\Metric as MetricContract; |
10
|
|
|
|
11
|
|
|
abstract class Metric implements MetricContract |
12
|
|
|
{ |
13
|
|
|
protected ?string $namespace = null; |
14
|
|
|
|
15
|
|
|
protected string $name; |
16
|
|
|
|
17
|
|
|
protected string $description; |
18
|
|
|
|
19
|
|
|
protected array $labels = []; |
20
|
|
|
|
21
|
|
|
protected static Storage $storage; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Metric constructor. |
25
|
|
|
* |
26
|
|
|
* @throws LabelException |
27
|
|
|
*/ |
28
|
114 |
|
public function __construct() |
29
|
|
|
{ |
30
|
114 |
|
foreach ($this->labels as $label) { |
31
|
82 |
|
if (!preg_match('/^(?![_]{2})[a-zA-Z_][a-zA-Z0-9_]*$/', $label)) { |
32
|
1 |
|
throw new LabelException("The label `{$label}` contains invalid characters."); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
113 |
|
if (!preg_match('/^[a-zA-Z_:][a-zA-Z0-9_:]*$/', $this->key())) { |
37
|
1 |
|
throw new PrometheusException("The metric name `{$this->key()}` contains invalid characters."); |
38
|
|
|
} |
39
|
112 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @return string |
43
|
|
|
*/ |
44
|
113 |
|
public function key(): string |
45
|
|
|
{ |
46
|
113 |
|
if (!$this->namespace()) { |
47
|
7 |
|
return $this->name(); |
48
|
|
|
} |
49
|
|
|
|
50
|
106 |
|
return "{$this->namespace()}_{$this->name()}"; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
abstract public function type(): string; |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return string|null |
60
|
|
|
*/ |
61
|
113 |
|
public function namespace(): ?string |
62
|
|
|
{ |
63
|
113 |
|
return $this->namespace; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @return string |
68
|
|
|
*/ |
69
|
113 |
|
public function name(): string |
70
|
|
|
{ |
71
|
113 |
|
return $this->name; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
32 |
|
public function description(): string |
78
|
|
|
{ |
79
|
32 |
|
return $this->description; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @return Collection |
84
|
|
|
*/ |
85
|
97 |
|
public function labels(): Collection |
86
|
|
|
{ |
87
|
97 |
|
return new Collection($this->labels); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* @param Storage $storage |
92
|
|
|
*/ |
93
|
31 |
|
public static function storeUsing(Storage $storage): void |
94
|
|
|
{ |
95
|
31 |
|
static::$storage = $storage; |
96
|
31 |
|
} |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* @return Storage |
100
|
|
|
*/ |
101
|
31 |
|
public static function storage(): Storage |
102
|
|
|
{ |
103
|
31 |
|
return static::$storage; |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|