This repository has been archived by the owner on May 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 801
/
Yaml.php
executable file
·415 lines (372 loc) · 12.9 KB
/
Yaml.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
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Config
*/
require_once 'Zend/Config.php';
/**
* YAML Adapter for Zend_Config
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Yaml extends Zend_Config
{
/**
* Attribute name that indicates what section a config extends from
*/
const EXTENDS_NAME = "_extends";
/**
* Whether to skip extends or not
*
* @var boolean
*/
protected $_skipExtends = false;
/**
* What to call when we need to decode some YAML?
*
* @var callable
*/
protected $_yamlDecoder = array(__CLASS__, 'decode');
/**
* Whether or not to ignore constants in parsed YAML
* @var bool
*/
protected static $_ignoreConstants = false;
/**
* Indicate whether parser should ignore constants or not
*
* @param bool $flag
* @return void
*/
public static function setIgnoreConstants($flag)
{
self::$_ignoreConstants = (bool) $flag;
}
/**
* Whether parser should ignore constants or not
*
* @return bool
*/
public static function ignoreConstants()
{
return self::$_ignoreConstants;
}
/**
* Get callback for decoding YAML
*
* @return callable
*/
public function getYamlDecoder()
{
return $this->_yamlDecoder;
}
/**
* Set callback for decoding YAML
*
* @param callable $yamlDecoder the decoder to set
* @return Zend_Config_Yaml
*/
public function setYamlDecoder($yamlDecoder)
{
if (!is_callable($yamlDecoder)) {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Invalid parameter to setYamlDecoder() - must be callable');
}
$this->_yamlDecoder = $yamlDecoder;
return $this;
}
/**
* Loads the section $section from the config file encoded as YAML
*
* Sections are defined as properties of the main object
*
* In order to extend another section, a section defines the "_extends"
* property having a value of the section name from which the extending
* section inherits values.
*
* Note that the keys in $section will override any keys of the same
* name in the sections that have been included via "_extends".
*
* Options may include:
* - allow_modifications: whether or not the config object is mutable
* - skip_extends: whether or not to skip processing of parent configuration
* - yaml_decoder: a callback to use to decode the Yaml source
*
* @param string $yaml YAML file to process
* @param mixed $section Section to process
* @param array|boolean $options
*/
public function __construct($yaml, $section = null, $options = false)
{
if (empty($yaml)) {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Filename is not set');
}
$ignoreConstants = $staticIgnoreConstants = self::ignoreConstants();
$allowModifications = false;
if (is_bool($options)) {
$allowModifications = $options;
} elseif (is_array($options)) {
foreach ($options as $key => $value) {
switch (strtolower($key)) {
case 'allow_modifications':
case 'allowmodifications':
$allowModifications = (bool) $value;
break;
case 'skip_extends':
case 'skipextends':
$this->_skipExtends = (bool) $value;
break;
case 'ignore_constants':
case 'ignoreconstants':
$ignoreConstants = (bool) $value;
break;
case 'yaml_decoder':
case 'yamldecoder':
$this->setYamlDecoder($value);
break;
default:
break;
}
}
}
// Suppress warnings and errors while loading file
set_error_handler(array($this, '_loadFileErrorHandler'));
$yaml = file_get_contents($yaml);
restore_error_handler();
// Check if there was a error while loading file
if ($this->_loadFileErrorStr !== null) {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception($this->_loadFileErrorStr);
}
// Override static value for ignore_constants if provided in $options
self::setIgnoreConstants($ignoreConstants);
// Parse YAML
$config = call_user_func($this->getYamlDecoder(), $yaml);
// Reset original static state of ignore_constants
self::setIgnoreConstants($staticIgnoreConstants);
if (null === $config) {
// decode failed
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Error parsing YAML data");
}
if (null === $section) {
$dataArray = array();
foreach ($config as $sectionName => $sectionData) {
$dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
}
parent::__construct($dataArray, $allowModifications);
} elseif (is_array($section)) {
$dataArray = array();
foreach ($section as $sectionName) {
if (!isset($config[$sectionName])) {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf(
'Section "%s" cannot be found',
implode(' ', (array)$section)
));
}
$dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
}
parent::__construct($dataArray, $allowModifications);
} else {
if (!isset($config[$section])) {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf(
'Section "%s" cannot be found',
implode(' ', (array)$section)
));
}
$dataArray = $this->_processExtends($config, $section);
if (!is_array($dataArray)) {
// Section in the yaml data contains just one top level string
$dataArray = array($section => $dataArray);
}
parent::__construct($dataArray, $allowModifications);
}
$this->_loadedSection = $section;
}
/**
* Helper function to process each element in the section and handle
* the "_extends" inheritance attribute.
*
* @param array $data Data array to process
* @param string $section Section to process
* @param array $config Configuration which was parsed yet
* @return array
* @throws Zend_Config_Exception When $section cannot be found
*/
protected function _processExtends(array $data, $section, array $config = array())
{
if (!isset($data[$section])) {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $section));
}
$thisSection = $data[$section];
if (is_array($thisSection) && isset($thisSection[self::EXTENDS_NAME])) {
$this->_assertValidExtend($section, $thisSection[self::EXTENDS_NAME]);
if (!$this->_skipExtends) {
$config = $this->_processExtends($data, $thisSection[self::EXTENDS_NAME], $config);
}
unset($thisSection[self::EXTENDS_NAME]);
}
$config = $this->_arrayMergeRecursive($config, $thisSection);
return $config;
}
/**
* Very dumb YAML parser
*
* Until we have Zend_Yaml...
*
* @param string $yaml YAML source
* @return array Decoded data
*/
public static function decode($yaml)
{
$lines = explode("\n", $yaml);
reset($lines);
return self::_decodeYaml(0, $lines);
}
/**
* Service function to decode YAML
*
* @param int $currentIndent Current indent level
* @param array $lines YAML lines
* @return array|string
*/
protected static function _decodeYaml($currentIndent, &$lines)
{
$config = array();
$inIndent = false;
while (list($n, $line) = each($lines)) {
$lineno = $n + 1;
$line = rtrim(preg_replace("/#.*$/", "", $line));
if (strlen($line) == 0) {
continue;
}
$indent = strspn($line, " ");
// line without the spaces
$line = trim($line);
if (strlen($line) == 0) {
continue;
}
if ($indent < $currentIndent) {
// this level is done
prev($lines);
return $config;
}
if (!$inIndent) {
$currentIndent = $indent;
$inIndent = true;
}
if (preg_match("/(?!-)([\w\-]+):\s*(.*)/", $line, $m)) {
// key: value
if (strlen($m[2])) {
// simple key: value
$value = preg_replace("/#.*$/", "", $m[2]);
$value = self::_parseValue($value);
} else {
// key: and then values on new lines
$value = self::_decodeYaml($currentIndent + 1, $lines);
if (is_array($value) && !count($value)) {
$value = "";
}
}
$config[$m[1]] = $value;
} elseif ($line[0] == "-") {
// item in the list:
// - FOO
if (strlen($line) > 2) {
$value = substr($line, 2);
$config[] = self::_parseValue($value);
} else {
$config[] = self::_decodeYaml($currentIndent + 1, $lines);
}
} else {
require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf(
'Error parsing YAML at line %d - unsupported syntax: "%s"',
$lineno, $line
));
}
}
return $config;
}
/**
* Parse values
*
* @param string $value
* @return string
*/
protected static function _parseValue($value)
{
$value = trim($value);
// remove quotes from string.
if ('"' == $value['0']) {
if ('"' == $value[count($value) -1]) {
$value = substr($value, 1, -1);
}
} elseif ('\'' == $value['0'] && '\'' == $value[count($value) -1]) {
$value = strtr($value, array("''" => "'", "'" => ''));
}
// Check for booleans and constants
if (preg_match('/^(t(rue)?|on|y(es)?)$/i', $value)) {
$value = true;
} elseif (preg_match('/^(f(alse)?|off|n(o)?)$/i', $value)) {
$value = false;
} elseif (strcasecmp($value, 'null') === 0) {
$value = null;
} elseif (!self::$_ignoreConstants) {
// test for constants
$value = self::_replaceConstants($value);
}
return $value;
}
/**
* Replace any constants referenced in a string with their values
*
* @param string $value
* @return string
*/
protected static function _replaceConstants($value)
{
foreach (self::_getConstants() as $constant) {
if (strstr($value, $constant)) {
$value = str_replace($constant, constant($constant), $value);
}
}
return $value;
}
/**
* Get (reverse) sorted list of defined constant names
*
* @return array
*/
protected static function _getConstants()
{
$constants = array_keys(get_defined_constants());
rsort($constants, SORT_STRING);
return $constants;
}
}