-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseConfigParser.php
437 lines (386 loc) · 12.2 KB
/
BaseConfigParser.php
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php
/**
* This file is part of NoiseLabs-PHP-ToolKit
*
* NoiseLabs-PHP-ToolKit is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* NoiseLabs-PHP-ToolKit is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with NoiseLabs-PHP-ToolKit; if not, see
* <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2011-2013 Vítor Brandão <vitor@noiselabs.org>
*
*
* @category NoiseLabs
* @package ConfigParser
* @copyright (C) 2011-2013 Vítor Brandão <vitor@noiselabs.org>
*/
namespace NoiseLabs\ToolKit\ConfigParser;
use NoiseLabs\ToolKit\ConfigParser\ParameterBag;
/**
* Base class for ConfigParser classes.
*
* @author Vítor Brandão <vitor@noiselabs.org>
*/
abstract class BaseConfigParser implements \ArrayAccess, \IteratorAggregate, \Countable
{
const VERSION = '0.2.0-BETA2';
/**
* A set of internal options used when parsing and writing files.
*
* Known settings:
*
* 'delimiter':
* The delimiter character to use between keys and values.
* Defaults to '='.
*
* 'space_around_delimiters':
* Put a blank space between keys/values and delimiters?
* Defaults to TRUE.
*
* 'linebreak':
* The linebreak to use.
* Defaults to '\r\n' on Windows OS and '\n' on every other OS.
*
* 'interpolation':
* @todo: Describe the interpolation mecanism.
* Defaults to FALSE.
*/
public $settings = array();
/**
*
* @var array
*/
protected $_defaults = array();
/**
* The configuration representation is stored here.
* @var array
*/
protected $_sections = array();
/**
* Comment lines are stored here so they can make it to the destination
* file.
*
* @var array $_comments
*/
protected $_comments;
/**
* An array of FILE objects representing the loaded files.
* @var array
*/
protected $_files = array();
/**
* Booleans alias
* @var array
*/
protected $_boolean_states = array(
'1' => true,
'yes' => True,
'true' => true,
'on' => true,
'0' => false,
'no' => false,
'false' => false,
'off' => false
);
/**
* Constructor.
*
* @param array $defaults
* @param array $settings
*/
public function __construct(array $defaults = array(), array $settings = array())
{
$this->_defaults = $defaults;
// default options
$this->settings = new ParameterBag(array(
'delimiter' => '=',
'space_around_delimiters' => true,
'linebreak' => PHP_EOL,
'throw_exceptions' => true,
'interpolation' => false,
'save_comments' => true
));
$this->settings->add($settings);
}
/**
* Return an associative array containing the instance-wide defaults.
*/
public function defaults()
{
return $this->_defaults;
}
/**
* Attempt to read and parse a list of filenames, returning a list of
* filenames which were successfully parsed. If filenames is a string, it
* is treated as a single filename. If a file named in filenames cannot be
* opened, that file will be ignored. This is designed so that you can
* specify a list of potential configuration file locations (for example,
* the current directory, the user’s home directory, and some system-wide
* directory), and all existing configuration files in the list will be
* read. If none of the named files exist, the ConfigParser instance will
* contain an empty dataset. An application which requires initial values
* to be loaded from a file should load the required file or files using
* read_file() before calling read() for any optional files:
*/
public function read($filenames = array())
{
if (!is_array($filenames)) {
$filenames = array($filenames);
}
foreach ($filenames as $filename) {
if (is_readable($filename)) {
// register a new file...
$file = new File($filename, 'rb');
$this->_files[] = $file;
// ... and append configuration
$this->_sections = array_replace($this->_sections, $this->_read($file));
}
}
}
public function readFile($filehandler)
{
trigger_error(__METHOD__.' is not implemented yet');
}
public function readString($string)
{
$this->_sections = parse_ini_string($string, static::HAS_SECTIONS, INI_SCANNER_RAW);
}
public function readArray(array $array = array())
{
$this->_sections = $array;
}
/**
* Re-read configuration from all successfully parsed files.
*/
public function reload()
{
$filenames = array();
foreach ($this->_files as $file) {
$this->_sections = array_merge($this->_sections, $this->_read($file->getPathname()));
}
}
/**
* Write an .ini-format representation of the configuration state
*
* @throws RuntimeException if file is not writable
*/
public function write($filename)
{
$file = new File($filename);
if (!$file->open('wb')) {
$errmsg = 'Unable to write configuration as file '.$file->getPathname().' could not be opened for writing';
if ($this->_throwExceptions()) {
throw new \RuntimeException($errmsg);
} else {
$this->log($errmsg);
return false;
}
} elseif (!$file->isWritable()) {
$errmsg = 'Unable to write configuration as file '.$file->getPathname().' is not writable';
if ($this->_throwExceptions()) {
throw new \RuntimeException($errmsg);
} else {
$this->log($errmsg);
return false;
}
}
$file->write($this->_buildOutputString());
$file->close();
}
/**
* Returns the iterator for this group.
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->_sections);
}
/**
* Returns the number of sections (implements the \Countable interface).
*
* @return integer The number of sections
*/
public function count()
{
return count($this->_sections);
}
/**
* Write the stored configuration to the last file successfully parsed
* in $this->read().
*/
public function save()
{
$file = end($this->_files);
return $this->write($file->getPathname());
}
/**
* Removes all parsed data.
*
* @return void
*/
public function clear()
{
$this->_sections = array();
}
/**
* Output the current configuration representation.
*
* @return void
*/
public function dump()
{
return $this->_sections;
}
/**
* Prints to the screen the current string as it would be written to the
* configuration file.
*
* @return void
*/
public function output()
{
echo $this->_buildOutputString();
}
/**
* Remove the specified section from the configuration. If the section in
* fact existed, return TRUE. Otherwise return FALSE.
*/
public function removeSection($section)
{
if (true === $this->hasSection($section)) {
unset($this->_sections[$section]);
return true;
} else {
return false;
}
}
/**
* Returns true if the section exists (implements the \ArrayAccess
* interface).
*
* @param string $offset The name of the section
*
* @return Boolean true if the section exists, false otherwise
*/
public function offsetExists($offset)
{
return $this->hasSection($offset);
}
/**
* Returns the array of options associated with the section (implements
* the \ArrayAccess interface).
*
* @param string $offset The offset of the value to get
*
* @return mixed The array of options associated with the section
*/
public function offsetGet($offset)
{
return $this->hasSection($offset) ? $this->_sections[$offset] : null;
}
/**
* Adds an array of options to the given section (implements the
* \ArrayAccess interface).
*
* @param string $section The name of the section to insert $options.
* @param array $options The array of options to be added
*/
public function offsetSet($offset, $value)
{
$this->_sections[$offset] = $value;
}
/**
* Removes the child with the given name from the form (implements the
* \ArrayAccess interface).
*
* @param string $name The name of the child to be removed
*/
public function offsetUnset($name)
{
$this->remove($name);
}
public function log($message, $level = 'crit')
{
error_log($message);
}
/**
* Saves all comments into an internal variable to be used when writing the
* configuration to a file.
*
* @param string $filename
*/
protected function readComments($filename)
{
$this->_comments = file($filename);
foreach (array_keys($this->_comments) as $i) {
if (substr(trim($this->_comments[$i]), 0, 1) != ';') {
unset($this->_comments[$i]);
}
}
}
/**
* Note the usage of INI_SCANNER_RAW to avoid parser_ini_files from
* parsing options and transforming 'false' values to empty strings.
*/
protected function _read(File $file)
{
if (!$file->exists()) {
$errmsg = 'File '.$file->getPathname().' does not exist.';
if ($this->_throwExceptions()) {
throw new \RuntimeException($errmsg);
} else {
$this->log($errmsg);
return false;
}
}
if (true === $this->settings->get('save_comments')) {
$this->readComments($file->getPathname());
}
$contents = $this->sanitizeIniStructure($file->getContents());
return parse_ini_string($contents, static::HAS_SECTIONS, INI_SCANNER_RAW);
}
abstract protected function _buildOutputString();
protected function _throwExceptions()
{
return (false === $this->settings->get('throw_exceptions')) ? false : true;
}
/**
* Sanitize the INI file structure because parse_ini_string() doesn't like
* some of the features supported in Python's configparser.
*
* Hask marks:
* Since PHP version 5.3.0 "Hash marks (#) may no longer be used as comments
* and will throw a deprecation warning if used". To remain compatible with
* our Python counterpart we need make sure hash marks can be used in INI
* files so we replace them internally with semicolons (;) to please
* parse_ini_*() functions.
*
* @param string $contents File contents as they come from the file.
* @return string Sanitized contents
*/
protected function sanitizeIniStructure($contents)
{
$lines = explode("\n", $contents);
foreach (array_keys($lines) as $k) {
// remove leading whitespace
$lines[$k] = preg_replace('/(^\s*)(.*$)/', '${2}', $lines[$k]);
// replace hash marks with semicolons
$lines[$k] = preg_replace('/(^#)/', ';', $lines[$k], 1, $count);
// replace the delimiter ":" with "="
if ($count == 0) {
$lines[$k] = preg_replace('/([^:])(:)/', '${1} =', $lines[$k], 1, $count);
}
}
return implode("\n", $lines);
}
}