|
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 |
|
$data = @parse_ini_file($path, true); |
|
29
|
|
|
|
|
30
|
12 |
|
if (!$data) { |
|
31
|
6 |
|
$error = error_get_last(); |
|
32
|
|
|
|
|
33
|
|
|
// parse_ini_file() may return NULL but set no error if the file contains no parsable data |
|
34
|
6 |
|
if (!is_array($error)) { |
|
35
|
3 |
|
$error["message"] = "No parsable content in file."; |
|
36
|
2 |
|
} |
|
37
|
|
|
|
|
38
|
|
|
// if file contains no parsable data, no error is set, resulting in any previous error |
|
39
|
|
|
// persisting in error_get_last(). in php 7 this can be addressed with error_clear_last() |
|
40
|
6 |
|
if (function_exists("error_clear_last")) { |
|
41
|
2 |
|
error_clear_last(); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
6 |
|
throw new ParseException($error); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
6 |
|
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
|
3 |
|
protected function expandDottedKey($data) |
|
58
|
|
|
{ |
|
59
|
3 |
|
foreach ($data as $key => $value) { |
|
60
|
3 |
|
if (($found = strpos($key, '.')) !== false) { |
|
61
|
3 |
|
$newKey = substr($key, 0, $found); |
|
62
|
3 |
|
$remainder = substr($key, $found + 1); |
|
63
|
|
|
|
|
64
|
3 |
|
$expandedValue = $this->expandDottedKey(array($remainder => $value)); |
|
65
|
3 |
|
if (isset($data[$newKey])) { |
|
66
|
3 |
|
$data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue); |
|
67
|
2 |
|
} else { |
|
68
|
3 |
|
$data[$newKey] = $expandedValue; |
|
69
|
|
|
} |
|
70
|
3 |
|
unset($data[$key]); |
|
71
|
2 |
|
} |
|
72
|
2 |
|
} |
|
73
|
3 |
|
return $data; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* {@inheritDoc} |
|
78
|
|
|
*/ |
|
79
|
3 |
|
public static function getSupportedExtensions() |
|
80
|
|
|
{ |
|
81
|
3 |
|
return array('ini'); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|