|
1
|
|
|
<?php |
|
2
|
|
|
namespace suda\framework\server\config; |
|
3
|
|
|
|
|
4
|
|
|
use suda\framework\exception\JsonException; |
|
5
|
|
|
use suda\framework\exception\YamlException; |
|
6
|
|
|
use suda\component\arrayobject\ArrayDotAccess; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* 配置文件加载器 |
|
10
|
|
|
* 支持 yaml,yml,json,php,ini 做配置文件 |
|
11
|
|
|
*/ |
|
12
|
|
|
class ContentLoader |
|
13
|
|
|
{ |
|
14
|
|
|
public static function loadJson(string $path, array $extra = []):array |
|
15
|
|
|
{ |
|
16
|
|
|
$content = file_get_contents($path); |
|
17
|
|
|
$content = static::parseValue($content, $extra); |
|
18
|
|
|
$data = json_decode($content, true); |
|
19
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
|
20
|
|
|
throw new JsonException('load json config error : '.json_last_error()); |
|
21
|
|
|
} |
|
22
|
|
|
return $data; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public static function loadIni(string $path, array $extra = []):array |
|
26
|
|
|
{ |
|
27
|
|
|
$content = file_get_contents($path); |
|
28
|
|
|
$content = static::parseValue($content, $extra); |
|
29
|
|
|
return \parse_ini_string($content, true) ?: []; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public static function loadYaml(string $path, array $extra = []):array |
|
33
|
|
|
{ |
|
34
|
|
|
if (function_exists('yaml_parse')) { |
|
35
|
|
|
$name = 'yaml_parse'; |
|
36
|
|
|
} elseif (class_exists('Spyc')) { |
|
37
|
|
|
$name = 'Spyc::YAMLLoadString'; |
|
38
|
|
|
} else { |
|
39
|
|
|
throw new YamlException('load yaml config error : missing yaml extension or spyc', 1); |
|
40
|
|
|
} |
|
41
|
|
|
$content = file_get_contents($path); |
|
42
|
|
|
$content = static::parseValue($content, $extra); |
|
43
|
|
|
return \call_user_func_array($name, [$content]); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
protected static function parseValue(string $content, array $extra = []):string |
|
47
|
|
|
{ |
|
48
|
|
|
return preg_replace_callback('/\$\{(.+?)\}/', function ($matchs) use ($extra) { |
|
49
|
|
|
$name = $matchs[1]; |
|
50
|
|
|
if (($value = ArrayDotAccess::get($extra, $name, null)) !== null) { |
|
51
|
|
|
} elseif (defined($name)) { |
|
52
|
|
|
$value = constant($name); |
|
53
|
|
|
} |
|
54
|
|
|
return is_string($value)?trim(json_encode($value), '"'):$value; |
|
55
|
|
|
}, $content); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|