Completed
Pull Request — master (#91)
by
unknown
04:12
created

Ini::parse()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 7
cts 7
cp 1
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 10
nc 5
nop 1
crap 4
1
<?php
2
3
namespace mhndev\config\FileParser;
4
5
use mhndev\config\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
20
    /**
21
     * {@inheritDoc}
22
     * Parses an INI file as an array
23
     *
24 6
     * @throws ParseException If there is an error parsing the INI file
25
     */
26 6
    public function parse($path)
27
    {
28 6
        $data = @parse_ini_file($path, true);
29 3
30 3
        if (!$data) {
31
            $error = error_get_last();
32
33 3
            // parse_ini_file() may return NULL but set no error if the file contains no parsable data
34
            if (!is_array($error)) {
35
                $error["message"] = "No parsable content in file.";
36
            }
37
38
            // if file contains no parsable data, no error is set, resulting in any previous error
39 3
            // persisting in error_get_last(). in php 7 this can be addressed with error_clear_last()
40
            if (function_exists("error_clear_last")) {
41 3
                error_clear_last();
42
            }
43
44
            throw new ParseException($error);
45
        }
46
47
        return $this->expandDottedKey($data);
48
    }
49
50
    /**
51
     * Expand array with dotted keys to multidimensional array
52
     *
53
     * @param array $data
54
     *
55
     * @return array
56
     */
57
    protected function expandDottedKey($data)
58
    {
59
        foreach ($data as $key => $value) {
60
            if (($found = strpos($key, '.')) !== false) {
61
                $newKey = substr($key, 0, $found);
62
                $remainder = substr($key, $found + 1);
63
64
                $expandedValue = $this->expandDottedKey(array($remainder => $value));
65
                if (isset($data[$newKey])) {
66
                    $data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue);
67
                } else {
68
                    $data[$newKey] = $expandedValue;
69
                }
70
                unset($data[$key]);
71
            }
72
        }
73
        return $data;
74
    }
75
76
    /**
77
     * {@inheritDoc}
78
     */
79
    public static function getSupportedExtensions()
80
    {
81
        return array('ini');
82
    }
83
}
84