NetworkTrafficCollector   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 29
c 3
b 0
f 0
dl 0
loc 53
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A collect() 0 4 1
B calculateNetworkThroughput() 0 40 9
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Network;
4
5
use Startwind\Inventorio\Collector\BasicCollector;
6
use Startwind\Inventorio\Exec\File;
7
use Startwind\Inventorio\Metrics\Memory\Memory;
8
9
class NetworkTrafficCollector extends BasicCollector
10
{
11
    protected string $identifier = "NetworkThroughput";
12
13
    private const MEMORY_KEY = 'net_traffic_history';
14
15
    public function collect(): array
16
    {
17
        return [
18
            'eth0' => $this->calculateNetworkThroughput('eth0')
19
        ];
20
    }
21
22
    function calculateNetworkThroughput($interface): float
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
23
    {
24
        $memory = Memory::getInstance();
25
26
        $file = new File();
27
28
        if (!$file->fileExists('/proc/net/dev')) return 0;
29
30
        $lines = $file->getContents('/proc/net/dev', true);
31
        foreach ($lines as $line) {
32
            if (strpos($line, $interface . ':') !== false) {
33
                $parts = preg_split('/\s+/', trim($line));
34
                $rx = (int)$parts[1];
35
                $tx = (int)$parts[9];
36
                $total = $rx + $tx;
37
                break;
38
            }
39
        }
40
41
        if (!isset($total)) return 0;
42
43
        $history = $memory->getData(self::MEMORY_KEY) ?? [];
44
        $lastTotal = end($history);
45
46
        if (!$lastTotal) $lastTotal = 0;
47
48
        if (!empty($history) && $total < $lastTotal) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total does not seem to be defined for all execution paths leading up to this point.
Loading history...
49
            $memory->addData(self::MEMORY_KEY, $total);
50
            return $total;
51
        }
52
53
        if (!empty($history)) {
54
            $mb = $total - $lastTotal;
55
        } else {
56
            $mb = 0;
57
        }
58
59
        $memory->addData(self::MEMORY_KEY, $total);
60
61
        return $mb;
62
    }
63
}