TextRenderer::render()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Krenor\Prometheus\Renderer;
4
5
use Krenor\Prometheus\Sample;
6
use Tightenco\Collect\Support\Collection;
7
use Krenor\Prometheus\MetricFamilySamples;
8
use Krenor\Prometheus\Contracts\Renderable;
9
10
class TextRenderer implements Renderable
11
{
12
    public const CONTENT_TYPE = 'text/plain; version=0.0.4';
13
14
    /**
15
     * {@inheritdoc}
16
     */
17 34
    public function render(Collection $metrics): string
18
    {
19
        return $metrics
20 34
            ->flatMap(fn(MetricFamilySamples $family) => $this->transform($family))
21 34
            ->implode(PHP_EOL) . PHP_EOL;
22
    }
23
24
    /**
25
     * @param Collection $labels
26
     *
27
     * @return string
28
     */
29 32
    protected function serialize(Collection $labels): string
30
    {
31 32
        if ($labels->isEmpty()) {
32 1
            return '';
33
        }
34
35 31
        $quoted = $labels->map(fn(string $value) => "\"{$value}\"");
36
37 31
        $serialized = urldecode(
38 31
            http_build_query($quoted->toArray(), '', ',')
39
        );
40
41 31
        return "{{$serialized}}";
42
    }
43
44
    /**
45
     * @param MetricFamilySamples $family
46
     *
47
     * @return Collection
48
     */
49 32
    protected function transform(MetricFamilySamples $family): Collection
50
    {
51 32
        $metric = $family->metric();
52
53 32
        $lines = new Collection([
54 32
            "# HELP {$metric->key()} {$metric->description()}",
55 32
            "# TYPE {$metric->key()} {$metric->type()}",
56
        ]);
57
58 32
        $metrics = $family
59 32
            ->samples()
60 32
            ->map(fn(Sample $sample) => "{$sample->name()}{$this->serialize($sample->labels())} {$sample->value()}")
61 32
            ->values();
62
63 32
        return $lines->merge($metrics);
64
    }
65
}
66