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

SamplesBuilder::samples()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Krenor\Prometheus\Contracts;
4
5
use Closure;
6
use Krenor\Prometheus\Sample;
7
use Tightenco\Collect\Support\Collection;
8
9
abstract class SamplesBuilder
10
{
11
    /**
12
     * @var Metric
13
     */
14
    protected $metric;
15
16
    /**
17
     * @var Collection
18
     */
19
    protected $items;
20
21
    /**
22
     * SamplesCollector constructor.
23
     *
24
     * @param Metric $metric
25
     * @param Collection $items
26
     */
27 43
    public function __construct(Metric $metric, Collection $items)
28
    {
29 43
        $this->metric = $metric;
30 43
        $this->items = $items;
31 43
    }
32
33
    /**
34
     * @return Collection
35
     */
36 42
    public function samples(): Collection
37
    {
38
        return $this->group()->flatMap(function (Collection $group) {
39 41
            return $group->map($this->build($this->metric->key()));
40 42
        });
41
    }
42
43
    /**
44
     * @return mixed
45
     */
46
    abstract protected function initialize();
47
48
    /**
49
     * @return Collection
50
     */
51 43
    protected function group(): Collection
52
    {
53 43
        if ($this->metric->labels()->isEmpty() && $this->items->isEmpty()) {
54 1
            return new Collection([
55 1
                new Collection([
56 1
                    ['value' => $this->initialize()],
57
                ]),
58
            ]);
59
        }
60
61 42
        $labels = $this->metric->labels()->toArray();
62
63 42
        return $this->items
64
            ->map(function ($value, string $key) {
65 42
                return json_decode($key, true) + compact('value');
66
            })->reject(function (array $data) use ($labels) {
67 42
                return !array_key_exists('labels', $data)
68 42
                    ?: array_keys($data['labels']) !== $labels;
69
            })->mapToGroups(function (array $item) {
70
                return [
71 41
                    json_encode($item['labels']) => $item,
72
                ];
73 42
            })->sortKeys();
74
    }
75
76
    /**
77
     * @param string $name
78
     *
79
     * @return Closure
80
     */
81 25
    protected function build(string $name): Closure
82
    {
83
        return function (array $item) use ($name) {
84 25
            $value = $item['value'];
85 25
            $labels = new Collection($item['labels']);
86
87 25
            return new Sample($name, $value, $labels);
88 25
        };
89
    }
90
}
91