Passed
Push — master ( cd0ae5...3b7eff )
by Nils
02:33
created

ApacheConfigurationCollector::extractServerName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Application\WebServer\Apache;
4
5
use Startwind\Inventorio\Collector\BasicCollector;
6
7
class ApacheConfigurationCollector extends BasicCollector
8
{
9
    protected string $identifier = 'ApacheConfiguration';
10
11
    private string $sitesEnabledPath = '/etc/apache2/sites-enabled';
12
13
    public function collect(): array
14
    {
15
        return [
16
            'modules' => $this->getActiveApacheModules(),
17
            'nonLinkedSitesEnabled' => $this->getRealConfigFilesWithServerNames()
18
        ];
19
    }
20
21
    private function getActiveApacheModules(): array
22
    {
23
        $output = [];
24
        $returnVar = 0;
25
26
        exec('apache2ctl -M 2>&1', $output, $returnVar);
27
28
        if ($returnVar !== 0) {
29
            return [];
30
        }
31
32
        $modules = [];
33
34
        foreach ($output as $line) {
35
            if (preg_match('/^\s*([a-z_]+)_module/', $line, $matches)) {
36
                $modules[] = $matches[1];
37
            }
38
        }
39
40
        return $modules;
41
    }
42
43
    public function isApacheInstalled(): bool
44
    {
45
        $output = null;
46
        $returnVar = null;
47
        exec('which apache2ctl || which httpd', $output, $returnVar);
48
        return !empty($output);
49
    }
50
51
    private function getRealConfigFilesWithServerNames(): array
52
    {
53
        if (!$this->isApacheInstalled()) {
54
            return [];
55
        }
56
57
        if (!is_dir($this->sitesEnabledPath)) {
58
            return [];
59
        }
60
61
        $configFiles = scandir($this->sitesEnabledPath);
62
        $results = [];
63
64
        foreach ($configFiles as $file) {
65
            $filePath = $this->sitesEnabledPath . DIRECTORY_SEPARATOR . $file;
66
67
            if (is_file($filePath) && !is_link($filePath)) {
68
                $serverName = $this->extractServerName($filePath);
69
                $results[] = [
70
                    'file' => $file,
71
                    'serverName' => $serverName,
72
                ];
73
            }
74
        }
75
76
        return $results;
77
    }
78
79
    private function extractServerName(string $filePath): ?string
80
    {
81
        $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
82
        foreach ($lines as $line) {
83
            if (preg_match('/^\s*ServerName\s+(.+)$/i', $line, $matches)) {
84
                return trim($matches[1]);
85
            }
86
        }
87
        return null;
88
    }
89
}
90