1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Noodlehaus\FileParser; |
4
|
|
|
|
5
|
|
|
use Noodlehaus\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
|
|
|
* @throws ParseException If there is an error parsing the INI file |
25
|
|
|
*/ |
26
|
12 |
|
public function parse($path) |
27
|
|
|
{ |
28
|
12 |
|
set_error_handler(function($severity, $message, $file, $line) { |
29
|
|
|
throw new ParseException([ |
30
|
12 |
|
'severity' => $severity, |
31
|
6 |
|
'message' => $message, |
32
|
|
|
'file' => $file, |
33
|
|
|
'line' => $line |
34
|
6 |
|
]); |
35
|
3 |
|
}); |
36
|
2 |
|
|
37
|
|
|
$data = parse_ini_file($path, true); |
38
|
|
|
|
39
|
|
|
restore_error_handler(); |
40
|
6 |
|
|
41
|
2 |
|
if (!$data) { |
|
|
|
|
42
|
|
|
throw new ParseException(['message' => "No parsable content in file."]); |
43
|
|
|
} |
44
|
6 |
|
|
45
|
|
|
return $this->expandDottedKey($data); |
46
|
|
|
} |
47
|
6 |
|
|
48
|
|
|
/** |
49
|
|
|
* Expand array with dotted keys to multidimensional array |
50
|
|
|
* |
51
|
|
|
* @param array $data |
52
|
|
|
* |
53
|
|
|
* @return array |
54
|
|
|
*/ |
55
|
|
|
protected function expandDottedKey($data) |
56
|
|
|
{ |
57
|
3 |
|
foreach ($data as $key => $value) { |
58
|
|
|
if (($found = strpos($key, '.')) !== false) { |
59
|
3 |
|
$newKey = substr($key, 0, $found); |
60
|
3 |
|
$remainder = substr($key, $found + 1); |
61
|
3 |
|
|
62
|
3 |
|
$expandedValue = $this->expandDottedKey(array($remainder => $value)); |
63
|
|
|
if (isset($data[$newKey])) { |
64
|
3 |
|
$data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue); |
65
|
3 |
|
} else { |
66
|
3 |
|
$data[$newKey] = $expandedValue; |
67
|
2 |
|
} |
68
|
3 |
|
unset($data[$key]); |
69
|
|
|
} |
70
|
3 |
|
} |
71
|
2 |
|
return $data; |
72
|
2 |
|
} |
73
|
3 |
|
|
74
|
|
|
/** |
75
|
|
|
* {@inheritDoc} |
76
|
|
|
*/ |
77
|
|
|
public static function getSupportedExtensions() |
78
|
|
|
{ |
79
|
3 |
|
return array('ini'); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.