summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/linux-health/src/Network.php
blob: e0bad7d8d879a31e911b35450a3466efbd42a591 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php

namespace gipfl\LinuxHealth;

class Network
{
    public static function getInterfaceCounters($procFile = '/proc/net/dev')
    {
        // Header looks like this:
        // Inter-|   Receive                                                |  Transmit
        //  face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets
        //        (...from above line) errs drop fifo colls carrier compressed

        $lines = \file($procFile, FILE_IGNORE_NEW_LINES);
        \array_shift($lines);
        $headers = preg_split('/\|/', array_shift($lines));
        $rxHeaders = preg_split('/\s+/', $headers[1]);
        $txHeaders = preg_split('/\s+/', $headers[2]);

        $headers = [];
        foreach ($rxHeaders as $rx) {
            $headers[] = 'rx' . ucfirst($rx);
        }
        foreach ($txHeaders as $tx) {
            $headers[] = 'tx' . ucfirst($tx);
        }
        $interfaces = [];
        foreach ($lines as $line) {
            $parts = preg_split('/\s+|\|/', trim($line));
            $ifName = rtrim(array_shift($parts), ':');
            $interfaces[$ifName] = (object) array_combine($headers, $parts);
        }

        return $interfaces;
    }
}