Completed
Push — develop ( 28a887...d46380 )
by Stan
02:57
created

TextRenderer::serialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0078

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 13
ccs 7
cts 8
cp 0.875
crap 2.0078
rs 9.4285
c 0
b 0
f 0
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
    /**
13
     * {@inheritdoc}
14
     */
15 31
    public function render(Collection $metrics): string
16
    {
17
        $text = $metrics->flatMap(function (MetricFamilySamples $family) {
18 31
            return $this->transform($family);
19 31
        })->implode("\n");
20
21 31
        return "{$text}\n";
22
    }
23
24
    /**
25
     * @param Collection $labels
26
     *
27
     * @return string
28
     */
29 31
    protected function serialize(Collection $labels): string
30
    {
31
        $quoted = $labels->map(function (string $value) {
32 31
            return "\"{$value}\"";
33 31
        });
34
35 31
        $serialized = urldecode(
36 31
            http_build_query($quoted->toArray(), '', ',')
37
        );
38
39 31
        return !$serialized
40
            ? $serialized
41 31
            : "{{$serialized}}";
42
    }
43
44
    /**
45
     * @param MetricFamilySamples $family
46
     *
47
     * @return Collection
48
     */
49 31
    protected function transform(MetricFamilySamples $family): Collection
50
    {
51 31
        $metric = $family->metric();
52
53 31
        $lines = new Collection([
54 31
            "# HELP {$metric->key()} {$metric->description()}",
55 31
            "# TYPE {$metric->key()} {$metric->type()}",
56
        ]);
57
58
        $metrics = $family->samples()->map(function (Sample $sample) {
59 31
            return "{$sample->name()}{$this->serialize($sample->labels())} {$sample->value()}";
60 31
        })->values();
61
62 31
        return $lines->merge($metrics);
63
    }
64
}
65