Passed
Push — develop ( ea980c...b5584b )
by Stan
02:34
created

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