UptimeCollector   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

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

2 Methods

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