NetworkTrafficCollector::collect()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 1
b 0
f 0
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
}