1 | <?php |
||
10 | class IniObject |
||
11 | { |
||
12 | private $filename; |
||
13 | |||
14 | protected $config; |
||
15 | |||
16 | private $sections; |
||
17 | |||
18 | /** |
||
19 | * IniObject constructor. |
||
20 | * |
||
21 | * @param string|null $filename |
||
22 | * @param array $config |
||
23 | */ |
||
24 | 10 | public function __construct(?string $filename = null, array $config = []) |
|
25 | { |
||
26 | 10 | $data = false; |
|
27 | |||
28 | 10 | if (! count($config)) { |
|
29 | 10 | $this->initDefaultConfig(); |
|
30 | } |
||
31 | 10 | if ($filename && file_exists($filename)) { |
|
|
|||
32 | 10 | $data = parse_ini_file( |
|
33 | 10 | $filename, |
|
34 | 10 | true, |
|
35 | 10 | $this->config['strict'] ? INI_SCANNER_TYPED : INI_SCANNER_NORMAL |
|
36 | ); |
||
37 | } |
||
38 | 10 | if ($data) { |
|
39 | 10 | $this->sectionLoad($data); |
|
40 | 10 | $this->setFilename($filename); |
|
41 | } |
||
42 | 10 | } |
|
43 | |||
44 | /** |
||
45 | * @param array $data |
||
46 | * @throws InvalidArgumentException |
||
47 | */ |
||
48 | 10 | private function sectionLoad(array $data): void |
|
49 | { |
||
50 | 10 | if (! count($data)) { |
|
51 | throw new InvalidArgumentException('Data is not set'); |
||
52 | } |
||
53 | |||
54 | 10 | $sections = []; |
|
55 | 10 | foreach ($data as $sectionName => $params) { |
|
56 | 10 | $sections[$sectionName] = new Section($sectionName, $params); |
|
57 | } |
||
58 | |||
59 | 10 | $this->sections = $sections; |
|
60 | 10 | } |
|
61 | |||
62 | /** |
||
63 | * @param string $name |
||
64 | * @return Section |
||
65 | */ |
||
66 | 6 | public function getSection(string $name): Section |
|
67 | { |
||
68 | 6 | if (! isset($this->sections[$name])) { |
|
69 | 1 | throw new InvalidArgumentException('Section not found'); |
|
70 | } |
||
71 | |||
72 | 6 | return $this->sections[$name]; |
|
73 | } |
||
74 | |||
75 | /** |
||
76 | * @param string $name |
||
77 | */ |
||
78 | 1 | public function removeSection(string $name): void |
|
85 | |||
86 | 3 | public function addSection(string $name, array $section): void |
|
93 | |||
94 | 1 | public function updateSection(string $name, array $section): void |
|
101 | |||
102 | /** |
||
103 | * default config |
||
104 | */ |
||
105 | 10 | private function initDefaultConfig(): void |
|
112 | |||
113 | /** |
||
114 | * @param string $filename |
||
115 | */ |
||
116 | 10 | private function setFilename(?string $filename): void |
|
120 | |||
121 | 1 | public function __toString() |
|
122 | { |
||
123 | 1 | $return = ''; |
|
131 | |||
132 | /** |
||
133 | * @param string|null $filename |
||
134 | * @return bool |
||
135 | */ |
||
136 | 1 | public function save(string $filename = null): bool |
|
147 | } |
||
148 |
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: