|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace HexMakina\LocalFS\Text; |
|
4
|
|
|
|
|
5
|
|
|
class INI extends TextFile |
|
6
|
|
|
{ |
|
7
|
|
|
|
|
8
|
|
|
public static function from_array(array $array) : string |
|
9
|
|
|
{ |
|
10
|
|
|
$ret = '# INI Dump'; |
|
11
|
|
|
|
|
12
|
|
|
if (is_array(current($array))) { // with sections |
|
13
|
|
|
foreach ($array as $section => $data) { |
|
14
|
|
|
$ret .= PHP_EOL . PHP_EOL . self::section($section); |
|
15
|
|
|
foreach ($data as $key => $value) { |
|
16
|
|
|
$ret .= PHP_EOL . self::line($key, $value); |
|
17
|
|
|
} |
|
18
|
|
|
} |
|
19
|
|
|
} else { // no section |
|
20
|
|
|
foreach ($array as $key => $value) { |
|
21
|
|
|
$ret .= self::line($key, $value); |
|
22
|
|
|
} |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
return $ret; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public static function to_array(string $filepath, bool $with_sections = true, int $mode = INI_SCANNER_RAW) : ?array |
|
29
|
|
|
{ |
|
30
|
|
|
// https://secure.php.net/manual/en/function.parse-ini-file.php |
|
31
|
|
|
$ret = parse_ini_file($filepath, $with_sections, $mode); |
|
32
|
|
|
if($ret === false) |
|
33
|
|
|
return null; |
|
34
|
|
|
|
|
35
|
|
|
return $ret; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
|
|
39
|
|
|
private static function section($key) : string |
|
40
|
|
|
{ |
|
41
|
|
|
$key = self::format_key($key); |
|
42
|
|
|
return "[$key]"; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
private static function line($key, $val) : string |
|
46
|
|
|
{ |
|
47
|
|
|
$key = self::format_key($key); |
|
48
|
|
|
$val = self::format_key($val); |
|
49
|
|
|
return "$key=\"$val\""; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
// private static function format_value($value) |
|
53
|
|
|
// { |
|
54
|
|
|
// return str_replace('"', '\"',$value); |
|
55
|
|
|
// } |
|
56
|
|
|
|
|
57
|
|
|
private static function format_key($key) |
|
58
|
|
|
{ |
|
59
|
|
|
return str_replace(' ', '_', $key); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|