Passed
Push — develop ( 500084...288399 )
by Stan
09:28
created

SamplesBuilder::group()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 2
nop 0
dl 0
loc 24
ccs 13
cts 13
cp 1
crap 4
rs 9.7333
c 0
b 0
f 0
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
     * @var Metric
12
     */
13
    protected $metric;
14
15
    /**
16
     * @var Collection
17
     */
18
    protected $items;
19
20
    /**
21
     * SamplesCollector constructor.
22
     *
23
     * @param Metric $metric
24
     * @param Collection $items
25
     */
26
    public function __construct(Metric $metric, Collection $items)
27 47
    {
28
        $this->metric = $metric;
29 47
        $this->items = $items;
30 47
    }
31 47
32
    /**
33
     * @return Collection|Sample[]
34
     */
35
    public function samples(): Collection
36 46
    {
37
        return $this
38
            ->parse()
39 45
            ->map(function (array $data) {
40 46
                return new Sample(
41
                    $data['name'],
42
                    $data['value'],
43
                    new Collection($data['labels'])
44
                );
45
            });
46
    }
47
48
    /**
49
     * @return Collection
50
     */
51 47
    protected function parse(): Collection
52
    {
53 47
        $name = $this->metric->key();
54 4
        $labels = $this->metric->labels()->toArray();
55 4
56 4
        if (empty($labels) && $this->items->isEmpty()) {
57 4
            return (new Collection)
58
                ->push(['value' => 0] + compact('name', 'labels'));
59
        }
60
61
        return $this
62 43
            ->items
63
            ->map(function ($value, string $field) use ($name) {
64 43
                // Merge stored fields with the value and name to an array.
65
                return compact('name', 'value') + json_decode($field, true);
66 43
            })->reject(function (array $data) use ($labels) {
67
                // Filter out items lacking the key "labels" or where labels names don't match.
68 43
                return !array_key_exists('labels', $data)
69 43
                    ?: array_keys($data['labels']) !== $labels;
70
            })->sortBy('labels')
71
            ->values();
72 42
    }
73
}
74