Memory::addDataSet()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
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 hasData(string $key): bool
44
    {
45
       return array_key_exists($key, $this->data);
46
    }
47
48
    public function getData(string $key): array
49
    {
50
        return $this->data[$key] ?? [];
51
    }
52
53
    public function getLastData(string $key, $default = 0): float
54
    {
55
        if (!array_key_exists($key, $this->data)) {
56
            return $default;
57
        } else {
58
            return end($this->data[$key]) ?? $default;
59
        }
60
    }
61
62
    public function addDataSet(array $dataset): void
63
    {
64
        foreach ($dataset as $key => $value) {
65
            $this->addData($key, $value);
66
        }
67
    }
68
69
    public function getNumberOfGreaterThan(string $key, int $threshold): int
70
    {
71
        if (!array_key_exists($key, $this->data)) return 0;
72
73
        $count = 0;
74
75
        foreach ($this->data[$key] as $value) {
76
            if ($value >= $threshold) $count++;
77
        }
78
79
        return $count;
80
    }
81
82
    public function getDataSet(): array
83
    {
84
        return $this->data;
85
    }
86
87
    public function setCollection(array $collection): void
88
    {
89
        $this->collection = $collection;
90
    }
91
92
    public function getCollection(): array
93
    {
94
        return $this->collection;
95
    }
96
}