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

Ini   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 3
c 2
b 0
f 1
lcom 0
cbo 1
dl 0
loc 28
ccs 8
cts 8
cp 1
rs 10
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