SamplesBuilder::parse()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 20
ccs 12
cts 12
cp 1
cc 4
crap 4
rs 9.8666
1
<?php
2
3
namespace Krenor\Prometheus\Contracts;
4
5
use Krenor\Prometheus\Sample;
6
use Tightenco\Collect\Support\Collection;
7
8
abstract class SamplesBuilder
9
{
10
    /**
11
     * SamplesCollector constructor.
12
     *
13
     * @param Metric $metric
14
     * @param Collection $items
15
     */
16 47
    public function __construct(protected Metric $metric, protected Collection $items)
17
    {
18
        //
19 47
    }
20
21
    /**
22
     * @return Collection|Sample[]
23
     */
24 47
    public function samples(): Collection
25
    {
26
        return $this
27 47
            ->parse()
28 46
            ->map(fn(array $data) => new Sample($data['name'], $data['value'], new Collection($data['labels'])));
29
    }
30
31
    /**
32
     * @return Collection
33
     */
34 47
    protected function parse(): Collection
35
    {
36 47
        $name = $this->metric->key();
37 47
        $labels = $this->metric->labels()->toArray();
38
39 47
        if (empty($labels) && $this->items->isEmpty()) {
40 4
            return (new Collection)
41 4
                ->push(['value' => 0] + compact('name', 'labels'));
42
        }
43
44
        return $this
45 43
            ->items
46
            // TODO: Find out how to make this an arrow function.. compact doesnt work with outer scoped $name variable
47 43
            ->map(function ($value, string $field) use ($name) {
48
                // Merge stored fields with the value and name to an array.
49 43
                return compact('name', 'value') + json_decode($field, true);
50 43
            })->reject(fn(array $data) => !array_key_exists('labels', $data) ?: array_keys($data['labels']) !== $labels)
51
            // Filter out items lacking the key "labels" or where labels names don't match.
52 43
            ->sortBy('labels')
53 43
            ->values();
54
    }
55
}
56