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
|
|
|
|