Passed
Branch develop (c85352)
by Stan
02:28
created

Metric::storeUsing()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
    /**
14
     * @var string
15
     */
16
    protected $namespace;
17
18
    /**
19
     * @var string
20
     */
21
    protected $name;
22
23
    /**
24
     * @var string
25
     */
26
    protected $description;
27
28
    /**
29
     * @var string[]
30
     */
31
    protected $labels = [];
32
33
    /**
34
     * @var Storage
35
     */
36
    protected static $storage;
37
38
    /**
39
     * Metric constructor.
40
     *
41
     * @throws LabelException
42
     */
43 77
    public function __construct()
44
    {
45 77
        foreach ($this->labels as $label) {
46 70
            if (!preg_match('/^(?![_]{2})[a-zA-Z_][a-zA-Z0-9_]*$/', $label)) {
47 70
                throw new LabelException("The label `{$label}` contains invalid characters.");
48
            }
49
        }
50
51 76
        if (!preg_match('/^[a-zA-Z_:][a-zA-Z0-9_:]*$/', $this->key())) {
52 1
            throw new PrometheusException("The metric name `{$this->key()}` contains invalid characters.");
53
        }
54 75
    }
55
56
    /**
57
     * @return string
58
     */
59 76
    public function key(): string
60
    {
61 76
        return "{$this->namespace()}_{$this->name()}";
62
    }
63
64
    /**
65
     * @return string
66
     */
67
    abstract public function type(): string;
68
69
    /**
70
     * @return string
71
     */
72 76
    public function namespace(): string
73
    {
74 76
        return $this->namespace;
75
    }
76
77
    /**
78
     * @return string
79
     */
80 76
    public function name(): string
81
    {
82 76
        return $this->name;
83
    }
84
85
    /**
86
     * @return string
87
     */
88 32
    public function description(): string
89
    {
90 32
        return $this->description;
91
    }
92
93
    /**
94
     * @return Collection
95
     */
96 60
    public function labels(): Collection
97
    {
98 60
        return new Collection($this->labels);
99
    }
100
101
    /**
102
     * @param Storage $storage
103
     */
104 31
    public static function storeUsing(Storage $storage): void
105
    {
106 31
        static::$storage = $storage;
107 31
    }
108
109
    /**
110
     * @return Storage
111
     */
112 31
    public static function storage(): Storage
113
    {
114 31
        return static::$storage;
115
    }
116
}
117