Passed
Push — master ( 0e59e1...fddcd5 )
by Nils
02:37
created

Memory::getData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Metrics\Memory;
4
/**
5
 * @property array $data
6
 */
7
class Memory
8
{
9
    private const MEMORY_SIZE = 12; // one hour if every 5 minutes taken
10
11
    private static ?Memory $instance = null;
12
13
    private array $collection = [];
14
15
    private array $data = [];
16
17
    static public function getInstance(): Memory
18
    {
19
        if (self::$instance === null) {
20
            self::$instance = new self();
21
        }
22
23
        return self::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::instance could return the type null which is incompatible with the type-hinted return Startwind\Inventorio\Metrics\Memory\Memory. Consider adding an additional type-check to rule them out.
Loading history...
24
    }
25
26
    private function __construct()
27
    {
28
    }
29
30
    public function addData(string $key, float $value): void
31
    {
32
        if (!array_key_exists($key, $this->data)) {
33
            $this->data[$key] = [];
34
        }
35
36
        if (count($this->data[$key]) >= self::MEMORY_SIZE) {
37
            array_shift($this->data[$key]);
38
        }
39
40
        $this->data[$key][] = $value;
41
    }
42
43
    public function getData(string $key): array
44
    {
45
        return $this->data[$key] ?? [];
46
    }
47
48
    public function getLastData(string $key, $default = 0): float
49
    {
50
        return end($this->data[$key]) ?? $default;
51
    }
52
53
    public function addDataSet(array $dataset): void
54
    {
55
        foreach ($dataset as $key => $value) {
56
            $this->addData($key, $value);
57
        }
58
    }
59
60
    public function getNumberOfGreaterThan(string $key, int $threshold): int
61
    {
62
        if (!array_key_exists($key, $this->data)) return 0;
63
64
        $count = 0;
65
66
        foreach ($this->data[$key] as $value) {
67
            if ($value >= $threshold) $count++;
68
        }
69
70
        return $count;
71
    }
72
73
    public function getDataSet(): array
74
    {
75
        return $this->data;
76
    }
77
78
    public function setCollection(array $collection): void
79
    {
80
        $this->collection = $collection;
81
    }
82
83
    public function getCollection(): array
84
    {
85
        return $this->collection;
86
    }
87
}