-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigManager.php
More file actions
337 lines (328 loc) · 11.7 KB
/
ConfigManager.php
File metadata and controls
337 lines (328 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php
namespace Iriven;
/**
* Created by PhpStorm.
* User: IRIVEN FRANCE
* Date: 21/11/2015
* Time: 10:44
*/
use Exception;
class ConfigManager
{
/**
* Chemin complet du fichier de configuration
*/
private $targetFile;
private $Options = [];
/**
* tableau multidimensionnel contenant les donnée de configuration, initialement
* chargées depuis le fichier
*/
private $Config = [];
/**
* processeurs de fichier pris en charge par l'application
*/
private $availableDrivers = array('JSON', 'PHP','INI','YML');
private $defaultSection = 'runtime';
/**
* ConfigManager constructor.
* @param $filename
* @param $location
*/
public function __construct( $filename, $location=null )
{
$numargs = func_num_args();
try
{
if($numargs > 2)
throw new Exception('SETUP ERROR: configuration manager can accept only up to 2 parameters,'.$numargs.' given!');
$this->configureOptions($filename,$location);
$this->parseConfiguration($this->Options);
}
catch(Exception $a)
{
trigger_error($a->getMessage(),E_USER_ERROR);
}
return $this;
}
/**
* @param $section
* @param $item
* @return array|bool|mixed
*/
public function get($section=null, $item=null)
{
if($item) $item = trim(strtolower($item));
if($section) $section = trim(strtolower($section));
if(!count($this->Config)) return false;
if(!$section or !strlen($section)) return $this->Config;
if($section AND $item)
{
if(!isset($this->Config[$section]))
{
$key = $item;
$item = $section;
$section = $this->defaultSection;
if(!isset($this->Config[$section][$item][$key]))
return false;
return $this->Config[$section][$item][$key];
}
}
elseif(!$item or !strlen($item))
{
$item = $section;
if(isset($this->Config[$item])) return $this->Config[$item];
$section = $this->defaultSection;
}
if(!isset($this->Config[$section][$item])) return false;
return $this->Config[$section][$item];
}
/**
* @param $section
* @param $item
* @param $value
* @return bool
*/
public function set($section,$item=null,$value=null)
{
ob_start();
$numarg = func_num_args();
$arguments=func_get_args();
switch($numarg)
{
case 1:
if(!is_array($arguments[0])) return false;
$item=array_change_key_case($arguments[0], CASE_LOWER); $section=null; $value=null;
break;
case 2:
if(is_array($arguments[0])) return false;
$_arg = strtolower(trim($arguments[0]));
if(is_array($arguments[1])){ $section=$_arg; $item =array_change_key_case($arguments[1], CASE_LOWER);$value=null;}
else {$item = $_arg;$value=$arguments[1];$section=null;}
break;
default:
break;
}
$section = $section? trim(strtolower($section)) : $this->defaultSection;
if(!is_array($item))
{
if(!$value) return false;
$item=trim(strtolower($item));
if(!isset($this->Config[$section][$item]) or !is_array($this->Config[$section][$item])):
$this->Config[$section][$item]=$value;
else:
if(!is_array($value)) $value = array($value);
$this->Config[$section][$item] = array_merge($this->Config[$section][$item],$value);
endif;
}
else
{
if($value) return false;
$item = array_change_key_case($item, CASE_LOWER);
$sectionsize = count($this->Config[$section]);
$itemsize = count($item);
if($sectionsize)
{
if($itemsize=='1')
{
if(isset($this->Config[$section][key($item)]))
$this->Config[$section][key($item)] = array_merge($this->Config[$section][key($item)],$item[key($item)]);
else if(!is_numeric(key($item))) $this->Config[$section][key($item)]=$item[key($item)];
}
else $this->Config[$section] = array_merge($this->Config[$section],$item);
}
else $this->Config[$section] = $item;
}
$re = $this->Save();
ob_end_clean();
return $re;
}
/**
* @param $section
* @param $item
* @return bool
*/
public function del($section, $item=null)
{
$section = trim(strtolower($section));
if($item and strlen($item))
{
$item = trim(strtolower($item));
if(!isset($this->Config[$section]))
{
$key = $item;
$item = $section;
$section = $this->defaultSection;
if(isset($this->Config[$section][$item][$key]))
{
$itemSize=count($this->Config[$section][$item]);
if($itemSize>1) unset($this->Config[$section][$item][$key]);
else unset($this->Config[$section]);
}
}
else
{
$sectionSize=count($this->Config[$section]);
if(isset($this->Config[$section][$item]))
{
if($sectionSize>1) unset($this->Config[$section][$item]);
else unset($this->Config[$section]);
}
}
}
else
{
$item = $section;
if(!isset($this->Config[$item]))
{
$section = $this->defaultSection;
$defaultSectionSize = count($this->Config[$section]);
if(isset($this->Config[$section][$item]))
{
if($defaultSectionSize>1) unset($this->Config[$section][$item]);
else unset($this->Config[$section]);
}
}
else unset($this->Config[$item]);
}
return $this->Save();
}
/**
* @param $file
* @param $location
* @return array
* @throws Exception
*/
private function configureOptions($file,$location=null){
if(!is_string($file) or ($location and !is_string($location)))
throw new Exception('SETUP ERROR: configuration manager can accept string only parameters');
$default=[
'driver' => 'PHP',
'filename' => null,
'directory' => __DIR__,
];
$Options = [];
if($location)
$Options['directory']=rtrim($this->normalize($location),DIRECTORY_SEPARATOR);
else{
if(basename($file)!==$file)
$Options['directory']= rtrim($this->normalize(pathinfo($file,PATHINFO_DIRNAME)),DIRECTORY_SEPARATOR);
}
$Options['filename'] = basename($file);
if(strpos($Options['filename'],'.')!==false)
$Options['driver'] = strtoupper(pathinfo($Options['filename'], PATHINFO_EXTENSION));
else
$Options['filename']= $Options['filename'].'.'.strtolower($default['driver']);
if(!in_array($Options['driver'],$this->availableDrivers))
throw new Exception('ERROR: driver "'.$Options['driver'].'" not supported');
$this->Options = array_merge($default,$Options);
return $this->Options;
}
/**
* @param $path
* @param $relativeTo
* @return bool|string
*/
private function normalize($path, $relativeTo = null) {
$path = rtrim(preg_replace('#[/\\\\]+#', DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR);
$isAbsolute = stripos(PHP_OS, 'win')===0 ? preg_match('/^[A-Za-z]+:/', $path): !strncmp($path, DIRECTORY_SEPARATOR, 1);
if (!$isAbsolute)
{
if (!$relativeTo) $relativeTo = getcwd();
$path = $relativeTo.DIRECTORY_SEPARATOR.$path;
}
if (is_link($path) and ($parentPath = realpath(dirname($path))))
return $parentPath.DIRECTORY_SEPARATOR.$path;
if ($realpath = realpath($path)) return $realpath;
$parts = explode(DIRECTORY_SEPARATOR, trim($path, DIRECTORY_SEPARATOR));
while (end($parts) !== false)
{
array_pop($parts);
$attempt = stripos(PHP_OS, 'win')===0 ? implode(DIRECTORY_SEPARATOR, $parts): DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts);
if ($realpaths = realpath($attempt))
{
$path = $realpaths.substr($path, strlen($attempt));
break;
}
}
return $path;
}
/**
* @param array $options
* @return array|bool|mixed
*/
private function parseConfiguration($options=[])
{
try
{ $this->targetFile = $this->normalize($options['directory'].DIRECTORY_SEPARATOR.$options['filename']);
if(!file_exists($this->targetFile))
file_put_contents($this->targetFile,'',LOCK_EX);
switch($this->Options['driver'])
{
case 'JSON':
$this->Config = unserialize(json_decode(file_get_contents($this->targetFile), true));
break;
case 'INI':
$this->Config = parse_ini_file($this->targetFile, true);
break;
case 'YML':
$ndocs=0;
$this->Config = yaml_parse_file($this->targetFile,0,$ndocs);
break;
default:
if(!$this->Config = include $this->targetFile) $this->Config = [];
break;
}
}
catch(Exception $b)
{
trigger_error($b->getMessage(),E_USER_ERROR);
}
return $this->Config;
}
/**
* @return bool
*/
private function Save()
{
try {
$content = null;
switch($this->Options['driver'])
{
case 'JSON':
$content .= json_encode(serialize($this->Config));
break;
case 'INI':
$content .= '; @file generator: Iriven France Php "'.get_class($this).'" Class'.PHP_EOL;
$content .= '; @Last Update: '.date('Y-m-d H:i:s').PHP_EOL;
$content .= PHP_EOL;
foreach($this->Config as $section => $array)
{
is_array($array) or $array = array($array);
$content .= '[' . $section . ']'.PHP_EOL;
foreach( $array as $key => $value )
$content .= $key.' = '.$value.PHP_EOL;
$content .= PHP_EOL;
}
break;
case 'YML':
$content .= yaml_emit ($this->Config, YAML_UTF8_ENCODING , YAML_LN_BREAK );
break;
default:
$content .= '<?php'.PHP_EOL;
$content .= 'return ';
$content .= var_export($this->Config, true) . ';';
$content = preg_replace('/array\s+\(/', '[', $content);
$content = preg_replace('/,(\s+)\)/', '$1]', $content);
break;
}
file_put_contents($this->targetFile, $content, LOCK_EX);
}
catch (Exception $e)
{ trigger_error($e->getMessage(),E_USER_ERROR);}
return true;
}
/**
* fin de la classe
*/
}