Completed
Push — master ( 532b1f...89ab0b )
by Mr
04:53 queued 11s
created

Import::parse()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 12
cp 0
rs 9.8333
c 0
b 0
f 0
cc 2
nc 1
nop 0
crap 6
1
<?php
2
3
namespace OpenVPN;
4
5
use OpenVPN\Interfaces\ConfigInterface;
6
use SplFileObject;
7
use function strlen;
8
9
class Import
10
{
11
    /**
12
     * Lines of config file
13
     *
14
     * @var array
15
     */
16
    private $_lines = [];
17
18
    /**
19
     * Import constructor, can import file on starting
20
     *
21
     * @param string|null $filename
22
     */
23
    public function __construct(string $filename = null)
24
    {
25
        if (null !== $filename) {
26
            $this->read($filename);
27
        }
28
    }
29
30
    /**
31
     * Check if line is valid config line, TRUE if line is okay.
32
     * If empty line or line with comment then FALSE.
33
     *
34
     * @param string $line
35
     *
36
     * @return bool
37
     */
38
    private function isLine(string $line): bool
39
    {
40
        return !(
41
            // Empty lines
42
            preg_match('/^\n+|^[\t\s]*\n+/m', $line) ||
43
            // Lines with comments
44
            preg_match('/^#/m', $line)
45
        );
46
    }
47
48
    /**
49
     * Read configuration file line by line
50
     *
51
     * @param string $filename
52
     *
53
     * @return array Array with count of total and read lines
54
     */
55
    public function read(string $filename): array
56
    {
57
        $lines = ['total' => 0, 'read' => 0];
58
59
        // Open file as SPL object
60
        $file = new SplFileObject($filename);
61
62
        // Read line by line
63
        while (!$file->eof()) {
64
            $line = $file->fgets();
65
            // Save line only of not empty
66
            if ($this->isLine($line) && strlen($line) > 1) {
67
                $line           = trim(preg_replace('/\s+/', ' ', $line));
68
                $this->_lines[] = $line;
69
                $lines['read']++;
70
            }
71
            $lines['total']++;
72
        }
73
        return $lines;
74
    }
75
76
    /**
77
     * Parse readed lines
78
     *
79
     * @return \OpenVPN\Interfaces\ConfigInterface
80
     */
81
    public function parse(): ConfigInterface
82
    {
83
        $config = new Config();
84
        array_map(
85
            static function ($line) use ($config) {
86
                if (preg_match('/^(\S+)( (.*))?/', $line, $matches)) {
87
                    $config->set($matches[1], $matches[3] ?? true);
88
                }
89
            },
90
            $this->_lines
91
        );
92
        return $config;
93
    }
94
}
95