Passed
Push — master ( 95a367...593e2b )
by Nils
02:38
created

UptimeCollector   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 50
rs 10
wmc 11

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getIdentifier() 0 3 1
B collect() 0 35 10
1
<?php
2
3
namespace Startwind\Inventorio\Collector\System\General;
4
5
use Startwind\Inventorio\Collector\Collector;
6
7
/**
8
 * This collector returns details about the operating system.
9
 *
10
 * - family: the OS family (MacOs, Linux, Windows). Please use the provided constants.
11
 * - version: the OS version
12
 *
13
 */
14
class UptimeCollector implements Collector
15
{
16
    protected const COLLECTION_IDENTIFIER = 'Uptime';
17
18
    /**
19
     * @inheritDoc
20
     */
21
    public function getIdentifier(): string
22
    {
23
        return self::COLLECTION_IDENTIFIER;
24
    }
25
26
    /**
27
     * @inheritDoc
28
     */
29
    public function collect(): array
30
    {
31
        $os = PHP_OS_FAMILY;
32
33
        $date = false;
34
35
        if ($os === 'Linux') {
0 ignored issues
show
introduced by
The condition $os === 'Linux' is always true.
Loading history...
36
            if (file_exists("/proc/uptime")) {
37
                $uptime = file_get_contents("/proc/uptime");
38
                $uptime = explode(" ", $uptime);
39
                $seconds = floor((int)$uptime[0]);
40
                $bootTimestamp = time() - $seconds;
41
                $date = date(\DateTime::ATOM, (int)$bootTimestamp);
42
            }
43
        } elseif ($os === 'Darwin') { // macOS
44
            $output = shell_exec("sysctl -n kern.boottime");
45
            if (preg_match('/sec = (\d+)/', $output, $matches)) {
46
                $bootTimestamp = (int)$matches[1];
47
                $date = date(\DateTime::ATOM, $bootTimestamp);
48
            }
49
        } elseif ($os === 'Windows') {
50
            $output = shell_exec("net stats srv");
51
            if ($output && preg_match('/Statistik seit (.*)/i', $output, $matches)) {
52
                $bootTimeStr = trim($matches[1]);
53
                $bootTimestamp = strtotime($bootTimeStr);
54
                if ($bootTimestamp !== false) {
55
                    $date = date(\DateTime::ATOM, $bootTimestamp);
56
                }
57
            }
58
        }
59
60
        if ($date) {
61
            return ['date' => $date];
62
        } else {
63
            return [];
64
        }
65
    }
66
}
67