Lines
100.00%
12 / 12
Functions and Methods
100.00%
6 / 6
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| MetricFamily | 100.00% | 12 / 12 | 100.00% | 6 / 6 | 7 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| createWithSample | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 1 | |||||
| recordSample | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| recordHistogram | 100.00% | 5 / 5 | 100.00% | 1 / 1 | 2 | |||||
| hasSamples | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| listSamples | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Runtime\Metrics\Exposition; | |
| 6 | ||
| 7 | final class MetricFamily | |
| 8 | { | |
| 9 | private const string BUCKET_BOUND_LABEL = 'le'; | |
| 10 | ||
| 11 | /** @var list<MetricSample> */ | |
| 12 | private array $samples = []; | |
| 13 | ||
| 14 | /** | |
| 15 | * @param non-empty-string $name | |
| 16 | * @param list<non-empty-string> $labelNames | |
| 17 | */ | |
| 18 | public function __construct( | |
| 19 | public readonly string $name, | |
| 20 | public readonly string $help, | |
| 21 | public readonly MetricType $type, | |
| 22 | public readonly array $labelNames, | |
| 23 | ) {} | |
| 24 | ||
| 25 | /** @param non-empty-string $name */ | |
| 26 | public static function createWithSample(string $name, string $help, MetricType $type, MetricLabels $labels, int|float|bool $value): self | |
| 27 | { | |
| 28 | $family = new self($name, $help, $type, array_keys($labels->listValuesByName())); | |
| 29 | $family->recordSample($labels, $value); | |
| 30 | ||
| 31 | return $family; | |
| 32 | } | |
| 33 | ||
| 34 | public function recordSample(MetricLabels $labels, int|float|bool $value): void | |
| 35 | { | |
| 36 | $this->samples[] = new MetricSample(MetricSampleSuffix::None, $labels, (float) $value); | |
| 37 | } | |
| 38 | ||
| 39 | public function recordHistogram(MetricLabels $labels, Histogram $histogram): void | |
| 40 | { | |
| 41 | foreach ($histogram->buckets as $bucket) { | |
| 42 | $bucketLabels = $labels->withLabel(self::BUCKET_BOUND_LABEL, PrometheusNumber::formatValue($bucket->upperBound)); | |
| 43 | $this->samples[] = new MetricSample(MetricSampleSuffix::Bucket, $bucketLabels, $bucket->cumulativeCount); | |
| 44 | } | |
| 45 | ||
| 46 | $this->samples[] = new MetricSample(MetricSampleSuffix::Sum, $labels, $histogram->sum->toSeconds()); | |
| 47 | $this->samples[] = new MetricSample(MetricSampleSuffix::Count, $labels, $histogram->count); | |
| 48 | } | |
| 49 | ||
| 50 | public function hasSamples(): bool | |
| 51 | { | |
| 52 | return $this->samples !== []; | |
| 53 | } | |
| 54 | ||
| 55 | /** @return list<MetricSample> */ | |
| 56 | public function listSamples(): array | |
| 57 | { | |
| 58 | return $this->samples; | |
| 59 | } | |
| 60 | } |