Passed
Push — master ( 6bb14b...dc86bc )
by Nils
02:20
created

ApacheServerNameCollector::extractServerName()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
nc 6
nop 1
dl 0
loc 24
c 2
b 0
f 0
cc 5
rs 9.5555
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Application\WebServer\Apache;
4
5
use Startwind\Inventorio\Collector\Collector;
6
7
class ApacheServerNameCollector implements Collector
8
{
9
    private const CONFIG_DIRECTORY = '/etc/apache2/sites-enabled';
10
11
    public const COLLECTION_IDENTIFIER = 'ApacheServerName';
12
13
    public const FIELD_DOCUMENT_ROOT = 'documentRoot';
14
    public const FIELD_SERVER_NAME = 'serverName';
15
16
    public function getIdentifier(): string
17
    {
18
        return self::COLLECTION_IDENTIFIER;
19
    }
20
21
    public function collect(): array
22
    {
23
        if (!file_exists(self::CONFIG_DIRECTORY)) {
24
            return [];
25
        }
26
27
        $configurations = $this->getAllConfigurations(self::CONFIG_DIRECTORY);
28
        $result = [];
29
30
        if (count($configurations) == 0) {
31
            return [];
32
        }
33
34
        foreach ($configurations as $configuration) {
35
            $config = $this->extractServerData($configuration);
36
            $result[$config['serverName']] = $config;
37
        }
38
39
        return array_values($result);
40
    }
41
42
    private function extractServerData(string $vhostFile): array
43
    {
44
        $lines = file($vhostFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
45
46
        $serverName = '';
47
        $aliases = [];
48
        $documentRoot = '';
49
50
        foreach ($lines as $line) {
51
            $line = trim($line);
52
53
            if (preg_match('/^\s*(#|\/\/)/', $line)) {
54
                continue;
55
            }
56
57
            if (preg_match('/^ServerName\s+([^\s]+)/i', $line, $match)) {
58
                $serverName = $match[1];
59
            }
60
61
            if (preg_match('/^ServerAlias\s+(.+)/i', $line, $match)) {
62
                $aliases[] = preg_split('/\s+/', trim($match[1]));
63
            }
64
65
            if (preg_match('/DocumentRoot\s+(.+)/', $line, $matches)) {
66
                $documentRoot = trim($matches[1]);
67
            }
68
        }
69
70
        return [
71
            self::FIELD_SERVER_NAME => $serverName,
72
            self::FIELD_DOCUMENT_ROOT => $documentRoot,
73
            'aliases' => $aliases
74
        ];
75
    }
76
77
    private function getAllConfigurations(string $vhostDir): array
78
    {
79
        $configurations = [];
80
81
        foreach (glob($vhostDir . '/*.conf') as $file) {
82
            $configurations[] = $file;
83
        }
84
85
        return $configurations;
86
    }
87
}
88