Completed
Pull Request — master (#111)
by Filip
07:42
created

Ini   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 1
dl 0
loc 58
ccs 24
cts 26
cp 0.9231
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 23 4
A expandDottedKey() 0 18 4
1
<?php
2
3
namespace Noodlehaus\StringParser;
4
5
use Noodlehaus\Exception\ParseException;
6
7
/**
8
 * INI string 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 StringParserInterface
17
{
18
    /**
19
     * {@inheritDoc}
20
     * Parses an INI string as an array
21
     *
22
     * @throws ParseException If there is an error parsing the INI string
23
     */
24 12
    public function parse($configuration)
25
    {
26 12
        $data = @parse_ini_string($configuration, true);
27
28 12
        if (!$data) {
29 6
            $error = error_get_last();
30
31
            // parse_ini_string() may return NULL but set no error if the string contains no parsable data
32 6
            if (!is_array($error)) {
33 2
                $error["message"] = "No parsable content in string.";
34
            }
35
36
            // if string contains no parsable data, no error is set, resulting in any previous error
37
            // persisting in error_get_last(). in php 7 this can be addressed with error_clear_last()
38 6
            if (function_exists("error_clear_last")) {
39 4
                error_clear_last();
40
            }
41
42 6
            throw new ParseException($error);
43
        }
44
45 6
        return $this->expandDottedKey($data);
46
    }
47
48
    /**
49
     * Expand array with dotted keys to multidimensional array
50
     *
51
     * @param array $data
52
     *
53
     * @return array
54
     */
55 3
    protected function expandDottedKey($data)
56
    {
57 3
        foreach ($data as $key => $value) {
58 3
            if (($found = strpos($key, '.')) !== false) {
59 3
                $newKey = substr($key, 0, $found);
60 3
                $remainder = substr($key, $found + 1);
61
62 3
                $expandedValue = $this->expandDottedKey([$remainder => $value]);
63 3
                if (isset($data[$newKey])) {
64 3
                    $data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue);
65 1
                } else {
66 3
                    $data[$newKey] = $expandedValue;
67
                }
68 3
                unset($data[$key]);
69 1
            }
70 1
        }
71 3
        return $data;
72
    }
73
}
74