Aggregator::stop()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Metrics aggregator
4
 * User: moyo
5
 * Date: 28/12/2017
6
 * Time: 5:56 PM
7
 */
8
9
namespace Carno\Monitor\Collector;
10
11
use Carno\Monitor\Daemon;
12
use Carno\Promise\Promise;
13
use Carno\Promise\Promised;
14
use Carno\Timer\Timer;
15
16
class Aggregator
17
{
18
    /**
19
     * @var array
20
     */
21
    private $metrics = [];
22
23
    /**
24
     * @var Daemon
25
     */
26
    private $source = null;
27
28
    /**
29
     * @var string
30
     */
31
    private $timer = null;
32
33
    /**
34
     * @var int
35
     */
36
    private $cycled = null;
37
38
    /**
39
     * Aggregation constructor.
40
     * @param Daemon $daemon
41
     * @param int $cycled
42
     */
43
    public function __construct(Daemon $daemon, int $cycled = 2)
44
    {
45
        $this->source = $daemon;
46
        $this->cycled = $cycled;
47
    }
48
49
    /**
50
     * @return array
51
     */
52
    public function metrics() : array
53
    {
54
        return $this->metrics;
55
    }
56
57
    /**
58
     * @return static
59
     */
60
    public function start() : self
61
    {
62
        $this->timer = Timer::loop($this->cycled * 1000, function () {
63
            $metrics = [];
64
65
            $this->source->spouting(static function (
66
                string $typed,
67
                string $named,
68
                string $grouped,
69
                string $description,
70
                array $labels,
71
                array $data
72
            ) use (&$metrics) {
73
                $metrics[$typed][$named][$grouped] = [$data, $labels, $description];
74
            });
75
76
            $this->metrics = $metrics;
77
        });
78
79
        return $this;
80
    }
81
82
    /**
83
     * @return Promised
84
     */
85
    public function stop() : Promised
86
    {
87
        Timer::clear($this->timer);
88
        return Promise::resolved();
89
    }
90
}
91