Passed
Push — master ( 09abe6...8522f2 )
by Nils
02:23
created

DpkgPackageCollector   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getIdentifier() 0 3 1
A collectUpdatablePackages() 0 20 4
A collect() 0 9 2
A collectPackages() 0 24 4
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Package\Dpkg;
4
5
use Startwind\Inventorio\Collector\Collector;
6
use Startwind\Inventorio\Collector\OperatingSystem\OperatingSystemCollector;
7
8
/**
9
 * This collector returns details about all installed HomeBrew packages.
10
 */
11
class DpkgPackageCollector implements Collector
12
{
13
    protected const COLLECTION_IDENTIFIER = 'DpkgPackages';
14
15
    /**
16
     * @inheritDoc
17
     */
18
    public function getIdentifier(): string
19
    {
20
        return self::COLLECTION_IDENTIFIER;
21
    }
22
23
    /**
24
     * @inheritDoc
25
     */
26
    public function collect(): array
27
    {
28
        if (OperatingSystemCollector::getOsFamily() !== OperatingSystemCollector::OS_FAMILY_LINUX) {
29
            return [];
30
        }
31
32
        return [
33
            'packages' => $this->collectPackages(),
34
            'updatable' => $this->collectUpdatablePackages()
35
        ];
36
    }
37
38
    private function collectUpdatablePackages(): array
39
    {
40
        $output = shell_exec('apt list --upgradable 2>/dev/null');
41
        $lines = explode("\n", $output);
42
        array_shift($lines);
43
44
        $packages = [];
45
46
        foreach ($lines as $line) {
47
            if (trim($line) === '') continue;
48
49
            if (preg_match('/^([^\s\/]+)\/[^\s]+\s+([^\s]+).*upgradable from: ([^\]]+)/', $line, $matches)) {
50
                $packages[$matches[1]] = [
51
                    'currentVersion' => $matches[3],
52
                    'newVersion' => $matches[2]
53
                ];
54
            }
55
        }
56
57
        return $packages;
58
    }
59
60
    private function collectPackages(): array
61
    {
62
        $installed = shell_exec('command -v dpkg-query');
63
64
        if (!$installed) {
65
            return [];
66
        }
67
68
        $packages = shell_exec('dpkg-query -l');
69
70
        $packageLines = explode("\n", trim($packages));
71
72
        $installedPackages = [];
73
74
        foreach ($packageLines as $line) {
75
            if (str_starts_with($line, 'ii')) {
76
                $packageDetails = preg_split('/\s+/', $line);
77
                $packageName = $packageDetails[1];
78
                $packageVersion = $packageDetails[2];
79
                $installedPackages[$packageName] = [$packageVersion];
80
            }
81
        }
82
83
        return $installedPackages;
84
    }
85
}
86