Completed
Push — master ( c05391...d7ccd4 )
by Andre
01:52
created

Ini::expandValue()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace TheIconic\Config\Parser;
4
5
use TheIconic\Config\Exception\ParserException;
6
use Throwable;
7
8
/**
9
 * config file parser for ini files
10
 *
11
 * @package Shared\Helper\Config\Parser
12
 */
13
class Ini extends AbstractParser
14
{
15
16
    /**
17
     * parses an ini config file into a config array
18
     *
19
     * @param string $file
20
     * @return array
21
     */
22
    public function parse($file)
23
    {
24
        try {
25
            $config = parse_ini_string(file_get_contents($file), true);
26
27
            if (false === $config) {
28
                throw new ParserException(sprintf('Couldn\'t parse config file %s', $file));
29
            }
30
        } catch (Throwable $e) {
31
            throw new ParserException(sprintf('Couldn\'t parse config file %s', $file));
32
        }
33
34
        return $this->expand($config);
35
    }
36
37
    /**
38
     * @param $config
39
     * @return array
40
     */
41
    protected function expand($config)
42
    {
43
        $expanded = [];
44
45
        foreach ($config as $key => $value) {
46
            $segments = explode('.', $key);
47
48
            $tmp =& $expanded;
49
50
            while ($segment = array_shift($segments)) {
51
                if (!isset($tmp[$segment])) {
52
                    $tmp[$segment] = [];
53
                }
54
                $tmp =& $tmp[$segment];
55
            }
56
57
            $tmp = $this->expandValue($value);
58
        }
59
60
        return $expanded;
61
    }
62
63
    /**
64
     * @param mixed $value
65
     * @return mixed
66
     */
67
    protected function expandValue($value)
68
    {
69
        if (is_array($value)) {
70
            return $this->expand($value);
71
        }
72
73
        if (is_string($value) && in_array($value, ['true', 'false'])) {
74
            return ($value !== 'false');
75
        }
76
77
        return $value;
78
    }
79
}
80