Completed
Pull Request — master (#81)
by
unknown
05:50
created

Ini::expandDottedKey()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 14
cts 14
cp 1
rs 9.2
cc 4
eloc 12
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Noodlehaus\FileParser;
4
5
use Noodlehaus\Exception\ParseException;
6
7
/**
8
 * INI file parser
9
 *
10
 * @package    Config
11
 * @author     Jesus A. Domingo <[email protected]>
12
 * @author     Hassan Khan <[email protected]>
13
 * @link       https://github.com/noodlehaus/config
14
 * @license    MIT
15
 */
16
class Ini implements FileParserInterface
17
{
18
    /**
19
     * {@inheritDoc}
20
     * Parses an INI file as an array
21
     *
22
     * @throws ParseException If there is an error parsing the INI file
23
     */
24 9
    public function parse($path)
25
    {
26 9
        $data = @parse_ini_file($path, true);
27
28 9
        if (!$data) {
29 3
            $error = error_get_last();
30 3
            throw new ParseException($error);
31
        }
32
33 6
        return $this->expandDottedKey($data);
34
    }
35
36
    /**
37
     * Expand array with dotted keys to multidimensional array
38
     *
39
     * @param array $data
40
     *
41
     * @return array
42
     */
43 3
    protected function expandDottedKey($data)
44
    {
45 3
        foreach ($data as $key => $value) {
46 3
            if (($found = strpos($key, '.')) !== false) {
47 3
                $newKey = substr($key, 0, $found);
48 3
                $remainder = substr($key, $found + 1);
49
50 3
                $expandedValue = $this->expandDottedKey([$remainder => $value]);
51 3
                if (isset($data[$newKey])) {
52 3
                    $data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue);
53 2
                } else {
54 3
                    $data[$newKey] = $expandedValue;
55
                }
56 3
                unset($data[$key]);
57 2
            }
58 2
        }
59 3
        return $data;
60
    }
61
62
    /**
63
     * {@inheritDoc}
64
     */
65 3
    public static function getSupportedExtensions()
66
    {
67 3
        return array('ini');
68
    }
69
}
70