Completed
Push — master ( 3b1951...58d3fb )
by Lexey
02:23
created

Parser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 0
dl 0
loc 51
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B parse() 0 31 5
A isCommentOrEmpty() 0 4 2
1
<?php
2
3
namespace LF\EnvDiff\Env;
4
5
use InvalidArgumentException;
6
7
class Parser
8
{
9
    /**
10
     * @param string $path
11
     *
12
     * @return array
13
     *
14
     * @throws InvalidArgumentException
15
     */
16 30
    public function parse($path)
17
    {
18 30
        if (!is_file($path)) {
19 3
            throw new InvalidArgumentException(sprintf('The file "%s" does not exist', $path));
20
        }
21
22 28
        $file = fopen($path, 'rb');
23
24 28
        $number = 0;
25 28
        $env    = [];
26 28
        while (false === feof($file)) {
27 28
            $line = trim(fgets($file));
28 28
            $number++;
29
30 28
            if ($this->isCommentOrEmpty($line)) {
31 19
                continue;
32
            }
33 28
            if (false === strpos($line, '=')) {
34 4
                throw new InvalidArgumentException(
35 4
                    sprintf('Parse error at %d line: `%s` is not valid env value', $number, $line)
36 4
                );
37
            }
38
39 24
            list($name, $value) = explode('=', $line, 2);
40 24
            $env[trim($name)] = trim($value);
41 24
        }
42
43 24
        fclose($file);
44
45 24
        return $env;
46
    }
47
48
    /**
49
     * @param string $line
50
     *
51
     * @return bool
52
     */
53 28
    private function isCommentOrEmpty($line)
54
    {
55 28
        return (mb_strlen($line) === 0 || $line[0] === '#');
56
    }
57
}
58