DpkgPackageCollector   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 29
c 3
b 0
f 0
dl 0
loc 70
rs 10
wmc 11

4 Methods

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