1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class Ini |
4
|
|
|
* |
5
|
|
|
* @link https://www.icy2003.com/ |
6
|
|
|
* @author icy2003 <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2017, icy2003 |
8
|
|
|
*/ |
9
|
|
|
namespace icy2003\php\ihelpers; |
10
|
|
|
|
11
|
|
|
use icy2003\php\icomponents\file\LocalFile; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* 获取配置数组 |
15
|
|
|
* - 支持三种配置文件:自定义、JSON、XML,后两个不必说,自定义的格式为: |
16
|
|
|
* [配置名] = [配置值],一行一个配置,结果将去掉左右两边空白 |
17
|
|
|
*/ |
18
|
|
|
class Ini |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* 自定义 ini 配置 |
22
|
|
|
*/ |
23
|
|
|
const TYPE_INI = 'ini'; |
24
|
|
|
/** |
25
|
|
|
* JSON 配置 |
26
|
|
|
*/ |
27
|
|
|
const TYPE_JSON = 'json'; |
28
|
|
|
/** |
29
|
|
|
* XML 配置 |
30
|
|
|
*/ |
31
|
|
|
const TYPE_XML = 'xml'; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* 配置类型 |
35
|
|
|
* |
36
|
|
|
* @var string |
37
|
|
|
*/ |
38
|
|
|
protected $_type; |
39
|
|
|
/** |
40
|
|
|
* 文件路径 |
41
|
|
|
* |
42
|
|
|
* @var string |
43
|
|
|
*/ |
44
|
|
|
protected $_file; |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* 构造函数 |
48
|
|
|
* |
49
|
|
|
* @param string $file |
50
|
|
|
* @param string $type |
51
|
|
|
*/ |
52
|
|
|
public function __construct($file, $type = self::TYPE_INI) |
53
|
|
|
{ |
54
|
|
|
$this->_file = $file; |
55
|
|
|
$this->_type = $type; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* 转成数组 |
60
|
|
|
* |
61
|
|
|
* @return array |
62
|
|
|
*/ |
63
|
|
|
public function toArray() |
64
|
|
|
{ |
65
|
|
|
$local = new LocalFile(); |
66
|
|
|
$array = []; |
67
|
|
|
if (self::TYPE_INI === $this->_type) { |
68
|
|
|
foreach ($local->linesGenerator($this->_file, true) as $line) { |
69
|
|
|
// 如果 # 开头认为这是注释 |
70
|
|
|
if (Strings::isStartsWith(trim($line), '#')) { |
71
|
|
|
continue; |
72
|
|
|
} |
73
|
|
|
list($name, $value) = Arrays::lists(explode('=', $line), 2, function ($row) {return trim($row);}); |
74
|
|
|
$array[$name] = $value; |
75
|
|
|
// 如果值被 [] 包括,则以英文逗号为分割,将值变成数组 |
76
|
|
|
if (Strings::isStartsWith($value, '[') && Strings::isEndsWith($value, ']')) { |
77
|
|
|
$array[$name] = explode(',', Strings::sub($value, 1, -1)); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} elseif (self::TYPE_JSON === $this->_type) { |
81
|
|
|
$content = $local->getFileContent($this->_file); |
82
|
|
|
$array = Json::decode($content); |
83
|
|
|
} elseif (self::TYPE_XML === $this->_type) { |
84
|
|
|
$content = $local->getFileContent($this->_file); |
85
|
|
|
$array = Xml::toArray($content); |
86
|
|
|
} |
87
|
|
|
return $array; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|