Completed
Push — master ( b55a89...338c5a )
by Mr
07:01
created

Import::load()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.105

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 14
cp 0.8571
rs 8.9297
c 0
b 0
f 0
cc 6
nc 9
nop 2
crap 6.105
1
<?php
2
3
namespace OpenVPN;
4
5
use OpenVPN\Interfaces\ConfigInterface;
6
use OpenVPN\Interfaces\ImportInterface;
7
use function strlen;
8
9
class Import implements ImportInterface
10
{
11
    /**
12
     * Lines of config file
13
     *
14
     * @var array
15
     */
16
    public $lines = [];
17
18
    /**
19
     * Import constructor, can import file on starting
20
     *
21
     * @param string|null $filename  Path to config file
22
     * @param bool        $isContent If true, then path mean content of config file
23
     */
24 3
    public function __construct(string $filename = null, bool $isContent = false)
25
    {
26 3
        if ($isContent) {
27
            $this->load($filename);
28 3
        } elseif (null !== $filename) {
29
            $this->read($filename);
30
        }
31 3
    }
32
33
    /**
34
     * Check if line is valid config line, TRUE if line is okay.
35
     * If empty line or line with comment then FALSE.
36
     *
37
     * @param string $line
38
     *
39
     * @return bool
40
     */
41 2
    private function isLine(string $line): bool
42
    {
43
        return !(
44
            // Empty lines
45 2
            preg_match('/^\n+|^[\t\s]*\n+/m', $line) ||
46
            // Lines with comments
47 2
            preg_match('/^#/m', $line)
48
        );
49
    }
50
51
    /**
52
     * Read configuration file line by line
53
     *
54
     * @param string $filename
55
     *
56
     * @return array Array with count of total and read lines
57
     */
58 1
    public function read(string $filename): array
59
    {
60 1
        $content = file_get_contents($filename);
61 1
        return $this->load($content);
62
    }
63
64
    /**
65
     * Load content from text of config
66
     *
67
     * @param string $content Content of config file
68
     * @param string $type    Type of loaded content: raw (default), json
69
     *
70
     * @return array Array with count of total and read lines
71
     */
72 2
    public function load(string $content, string $type = 'raw'): array
73
    {
74 2
        $result = ['total' => 0, 'read' => 0];
75
76 2
        if ($type === 'raw') {
77 2
            $lines = explode("\n", $content);
78
        } elseif ($type === 'json') {
79
            $lines = json_decode($json, false);
0 ignored issues
show
Bug introduced by
The variable $json does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
80
        }
81
82
        // Read line by line
83 2
        foreach ($lines as $line) {
0 ignored issues
show
Bug introduced by
The variable $lines does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
84 2
            $line = trim($line);
85
            // Save line only of not empty
86 2
            if ($this->isLine($line) && strlen($line) > 1) {
87 2
                $line          = trim(preg_replace('/\s+/', ' ', $line));
88 2
                $this->lines[] = $line;
89 2
                $result['read']++;
90
            }
91 2
            $result['total']++;
92
        }
93 2
        return $result;
94
    }
95
96
    /**
97
     * Parse readed lines
98
     *
99
     * @return \OpenVPN\Interfaces\ConfigInterface
100
     */
101 3
    public function parse(): ConfigInterface
102
    {
103 3
        $config = new Config();
104 3
        array_map(
105
            static function ($line) use ($config) {
106 3
                if (preg_match('/^(\S+)( (.*))?/', $line, $matches)) {
107 3
                    $config->set($matches[1], $matches[3] ?? true);
108
                }
109 3
            },
110 3
            $this->lines
111
        );
112 3
        return $config;
113
    }
114
}
115