Completed
Push — develop ( 930556...77256d )
by Hassan
9s
created

Ini::parse()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 12
cts 13
cp 0.9231
rs 9.52
c 0
b 0
f 0
cc 4
nc 5
nop 2
crap 4.0072
1
<?php
2
3
namespace Noodlehaus\Parser;
4
5
use Noodlehaus\Exception\ParseException;
6
7
/**
8
 * INI parser
9
 *
10
 * @package    Config
11
 * @author     Jesus A. Domingo <[email protected]>
12
 * @author     Hassan Khan <[email protected]>
13
 * @author     Filip Š <[email protected]>
14
 * @link       https://github.com/noodlehaus/config
15
 * @license    MIT
16
 */
17
class Ini implements ParserInterface
18
{
19
20
21
    /**
22
     * {@inheritDoc}
23
     * Parses an INI string as an array
24
     *
25
     * @throws ParseException If there is an error parsing the INI string
26
     */
27 12
    public function parse($config, $filename = null)
28
    {
29 12
        $data = @parse_ini_string($config, true);
30
31 12
        if (!$data) {
32 6
            $error = error_get_last();
33
34
            // parse_ini_string() may return NULL but set no error if the string contains no parsable data
35 6
            if (!is_array($error)) {
36 3
                $error["message"] = "No parsable content in string.";
37 1
            }
38
39 6
            $error["file"] = $filename;
40
41
            // if string contains no parsable data, no error is set, resulting in any previous error
42
            // persisting in error_get_last(). in php 7 this can be addressed with error_clear_last()
43 6
            if (function_exists("error_clear_last")) {
44 4
                error_clear_last();
45
            }
46
47 6
            throw new ParseException($error);
48
        }
49
50 6
        return $this->expandDottedKey($data);
51
    }
52
53
    /**
54
     * Expand array with dotted keys to multidimensional array
55
     *
56
     * @param array $data
57
     *
58
     * @return array
59
     */
60 3
    protected function expandDottedKey($data)
61
    {
62 3
        foreach ($data as $key => $value) {
63 3
            if (($found = strpos($key, '.')) !== false) {
64 3
                $newKey = substr($key, 0, $found);
65 3
                $remainder = substr($key, $found + 1);
66
67 3
                $expandedValue = $this->expandDottedKey([$remainder => $value]);
68 3
                if (isset($data[$newKey])) {
69 3
                    $data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue);
70 1
                } else {
71 3
                    $data[$newKey] = $expandedValue;
72
                }
73 3
                unset($data[$key]);
74 1
            }
75 1
        }
76 3
        return $data;
77
    }
78
79
    /**
80
     * {@inheritDoc}
81
     */
82 3
    public static function getSupportedExtensions()
83
    {
84 3
        return ['ini'];
85
    }
86
}
87