[SPIP] +2.1.12
[velocampus/web/www.git] / www / plugins / auto / yaml / spyc / spyc.php
1 <?php
2 /**
3 * Spyc -- A Simple PHP YAML Class
4 * @version 0.4.5
5 * @author Vlad Andersen <vlad.andersen@gmail.com>
6 * @author Chris Wanstrath <chris@ozmm.org>
7 * @link http://code.google.com/p/spyc/
8 * @copyright Copyright 2005-2006 Chris Wanstrath, 2006-2009 Vlad Andersen
9 * @license http://www.opensource.org/licenses/mit-license.php MIT License
10 * @package Spyc
11 */
12
13 if (!function_exists('spyc_load')) {
14 /**
15 * Parses YAML to array.
16 * @param string $string YAML string.
17 * @return array
18 */
19 function spyc_load ($string) {
20 return Spyc::YAMLLoadString($string);
21 }
22 }
23
24 if (!function_exists('spyc_load_file')) {
25 /**
26 * Parses YAML to array.
27 * @param string $file Path to YAML file.
28 * @return array
29 */
30 function spyc_load_file ($file) {
31 return Spyc::YAMLLoad($file);
32 }
33 }
34
35 /**
36 * The Simple PHP YAML Class.
37 *
38 * This class can be used to read a YAML file and convert its contents
39 * into a PHP array. It currently supports a very limited subsection of
40 * the YAML spec.
41 *
42 * Usage:
43 * <code>
44 * $Spyc = new Spyc;
45 * $array = $Spyc->load($file);
46 * </code>
47 * or:
48 * <code>
49 * $array = Spyc::YAMLLoad($file);
50 * </code>
51 * or:
52 * <code>
53 * $array = spyc_load_file($file);
54 * </code>
55 * @package Spyc
56 */
57 class Spyc {
58
59 // SETTINGS
60
61 /**
62 * Setting this to true will force YAMLDump to enclose any string value in
63 * quotes. False by default.
64 *
65 * @var bool
66 */
67 public $setting_dump_force_quotes = false;
68
69 /**
70 * Setting this to true will forse YAMLLoad to use syck_load function when
71 * possible. False by default.
72 * @var bool
73 */
74 public $setting_use_syck_is_possible = false;
75
76
77
78 /**#@+
79 * @access private
80 * @var mixed
81 */
82 private $_dumpIndent;
83 private $_dumpWordWrap;
84 private $_containsGroupAnchor = false;
85 private $_containsGroupAlias = false;
86 private $path;
87 private $result;
88 private $LiteralPlaceHolder = '___YAML_Literal_Block___';
89 private $SavedGroups = array();
90 private $indent;
91 /**
92 * Path modifier that should be applied after adding current element.
93 * @var array
94 */
95 private $delayedPath = array();
96
97 /**#@+
98 * @access public
99 * @var mixed
100 */
101 public $_nodeId;
102
103 /**
104 * Load a valid YAML string to Spyc.
105 * @param string $input
106 * @return array
107 */
108 public function load ($input) {
109 return $this->__loadString($input);
110 }
111
112 /**
113 * Load a valid YAML file to Spyc.
114 * @param string $file
115 * @return array
116 */
117 public function loadFile ($file) {
118 return $this->__load($file);
119 }
120
121 /**
122 * Load YAML into a PHP array statically
123 *
124 * The load method, when supplied with a YAML stream (string or file),
125 * will do its best to convert YAML in a file into a PHP array. Pretty
126 * simple.
127 * Usage:
128 * <code>
129 * $array = Spyc::YAMLLoad('lucky.yaml');
130 * print_r($array);
131 * </code>
132 * @access public
133 * @return array
134 * @param string $input Path of YAML file or string containing YAML
135 */
136 public static function YAMLLoad($input) {
137 $Spyc = new Spyc;
138 return $Spyc->__load($input);
139 }
140
141 /**
142 * Load a string of YAML into a PHP array statically
143 *
144 * The load method, when supplied with a YAML string, will do its best
145 * to convert YAML in a string into a PHP array. Pretty simple.
146 *
147 * Note: use this function if you don't want files from the file system
148 * loaded and processed as YAML. This is of interest to people concerned
149 * about security whose input is from a string.
150 *
151 * Usage:
152 * <code>
153 * $array = Spyc::YAMLLoadString("---\n0: hello world\n");
154 * print_r($array);
155 * </code>
156 * @access public
157 * @return array
158 * @param string $input String containing YAML
159 */
160 public static function YAMLLoadString($input) {
161 $Spyc = new Spyc;
162 return $Spyc->__loadString($input);
163 }
164
165 /**
166 * Dump YAML from PHP array statically
167 *
168 * The dump method, when supplied with an array, will do its best
169 * to convert the array into friendly YAML. Pretty simple. Feel free to
170 * save the returned string as nothing.yaml and pass it around.
171 *
172 * Oh, and you can decide how big the indent is and what the wordwrap
173 * for folding is. Pretty cool -- just pass in 'false' for either if
174 * you want to use the default.
175 *
176 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
177 * you can turn off wordwrap by passing in 0.
178 *
179 * @access public
180 * @return string
181 * @param array $array PHP array
182 * @param int $indent Pass in false to use the default, which is 2
183 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
184 */
185 public static function YAMLDump($array,$indent = false,$wordwrap = false) {
186 $spyc = new Spyc;
187 return $spyc->dump($array,$indent,$wordwrap);
188 }
189
190
191 /**
192 * Dump PHP array to YAML
193 *
194 * The dump method, when supplied with an array, will do its best
195 * to convert the array into friendly YAML. Pretty simple. Feel free to
196 * save the returned string as tasteful.yaml and pass it around.
197 *
198 * Oh, and you can decide how big the indent is and what the wordwrap
199 * for folding is. Pretty cool -- just pass in 'false' for either if
200 * you want to use the default.
201 *
202 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
203 * you can turn off wordwrap by passing in 0.
204 *
205 * @access public
206 * @return string
207 * @param array $array PHP array
208 * @param int $indent Pass in false to use the default, which is 2
209 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
210 */
211 public function dump($array,$indent = false,$wordwrap = false) {
212 // Dumps to some very clean YAML. We'll have to add some more features
213 // and options soon. And better support for folding.
214
215 // New features and options.
216 if ($indent === false or !is_numeric($indent)) {
217 $this->_dumpIndent = 2;
218 } else {
219 $this->_dumpIndent = $indent;
220 }
221
222 if ($wordwrap === false or !is_numeric($wordwrap)) {
223 $this->_dumpWordWrap = 40;
224 } else {
225 $this->_dumpWordWrap = $wordwrap;
226 }
227
228 // New YAML document
229 $string = "---\n";
230
231 // Start at the base of the array and move through it.
232 if ($array) {
233 $array = (array)$array;
234 $first_key = key($array);
235
236 $previous_key = -1;
237 foreach ($array as $key => $value) {
238 $string .= $this->_yamlize($key,$value,0,$previous_key, $first_key);
239 $previous_key = $key;
240 }
241 }
242 return $string;
243 }
244
245 /**
246 * Attempts to convert a key / value array item to YAML
247 * @access private
248 * @return string
249 * @param $key The name of the key
250 * @param $value The value of the item
251 * @param $indent The indent of the current node
252 */
253 private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0) {
254 if (is_array($value)) {
255 if (empty ($value))
256 return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key);
257 // It has children. What to do?
258 // Make it the right kind of item
259 $string = $this->_dumpNode($key, NULL, $indent, $previous_key, $first_key);
260 // Add the indent
261 $indent += $this->_dumpIndent;
262 // Yamlize the array
263 $string .= $this->_yamlizeArray($value,$indent);
264 } elseif (!is_array($value)) {
265 // It doesn't have children. Yip.
266 $string = $this->_dumpNode($key, $value, $indent, $previous_key, $first_key);
267 }
268 return $string;
269 }
270
271 /**
272 * Attempts to convert an array to YAML
273 * @access private
274 * @return string
275 * @param $array The array you want to convert
276 * @param $indent The indent of the current level
277 */
278 private function _yamlizeArray($array,$indent) {
279 if (is_array($array)) {
280 $string = '';
281 $previous_key = -1;
282 $first_key = key($array);
283 foreach ($array as $key => $value) {
284 $string .= $this->_yamlize($key, $value, $indent, $previous_key, $first_key);
285 $previous_key = $key;
286 }
287 return $string;
288 } else {
289 return false;
290 }
291 }
292
293 /**
294 * Returns YAML from a key and a value
295 * @access private
296 * @return string
297 * @param $key The name of the key
298 * @param $value The value of the item
299 * @param $indent The indent of the current node
300 */
301 private function _dumpNode($key, $value, $indent, $previous_key = -1, $first_key = 0) {
302 // do some folding here, for blocks
303 if (is_string ($value) && ((strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false ||
304 strpos($value,"*") !== false || strpos($value,"#") !== false || strpos($value,"<") !== false || strpos($value,">") !== false || strpos ($value, ' ') !== false ||
305 strpos($value,"[") !== false || strpos($value,"]") !== false || strpos($value,"{") !== false || strpos($value,"}") !== false) || substr ($value, -1, 1) == ':')
306 ) {
307 $value = $this->_doLiteralBlock($value,$indent);
308 } else {
309 $value = $this->_doFolding($value,$indent);
310 }
311
312 if ($value === array()) $value = '[ ]';
313 if (in_array ($value, array ('true', 'TRUE', 'false', 'FALSE', 'y', 'Y', 'n', 'N', 'null', 'NULL'), true)) {
314 $value = $this->_doLiteralBlock($value,$indent);
315 }
316 if (trim ($value) != $value)
317 $value = $this->_doLiteralBlock($value,$indent);
318
319 if (is_bool($value)) {
320 $value = ($value) ? "true" : "false";
321 }
322
323 $spaces = str_repeat(' ',$indent);
324
325 if (is_int($key) && $key - 1 == $previous_key && $first_key===0) {
326 // It's a sequence
327 $string = $spaces.'- '.$value."\n";
328 } else {
329 if ($first_key===0) throw new Exception('Keys are all screwy. The first one was zero, now it\'s "'. $key .'"');
330 // It's mapped
331 if (strpos($key, ":") !== false) { $key = '"' . $key . '"'; }
332 $string = $spaces.$key.': '.$value."\n";
333 }
334 return $string;
335 }
336
337 /**
338 * Creates a literal block for dumping
339 * @access private
340 * @return string
341 * @param $value
342 * @param $indent int The value of the indent
343 */
344 private function _doLiteralBlock($value,$indent) {
345 if ($value === "\n") return '\n';
346 if (strpos($value, "\n") === false && strpos($value, "'") === false) {
347 return sprintf ("'%s'", $value);
348 }
349 if (strpos($value, "\n") === false && strpos($value, '"') === false) {
350 return sprintf ('"%s"', $value);
351 }
352 $exploded = explode("\n",$value);
353 $newValue = '|';
354 $indent += $this->_dumpIndent;
355 $spaces = str_repeat(' ',$indent);
356 foreach ($exploded as $line) {
357 $newValue .= "\n" . $spaces . ($line);
358 }
359 return $newValue;
360 }
361
362 /**
363 * Folds a string of text, if necessary
364 * @access private
365 * @return string
366 * @param $value The string you wish to fold
367 */
368 private function _doFolding($value,$indent) {
369 // Don't do anything if wordwrap is set to 0
370
371 if ($this->_dumpWordWrap !== 0 && is_string ($value) && strlen($value) > $this->_dumpWordWrap) {
372 $indent += $this->_dumpIndent;
373 $indent = str_repeat(' ',$indent);
374 $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
375 $value = ">\n".$indent.$wrapped;
376 } else {
377 if ($this->setting_dump_force_quotes && is_string ($value))
378 $value = '"' . $value . '"';
379 }
380
381
382 return $value;
383 }
384
385 // LOADING FUNCTIONS
386
387 private function __load($input) {
388 $Source = $this->loadFromSource($input);
389 return $this->loadWithSource($Source);
390 }
391
392 private function __loadString($input) {
393 $Source = $this->loadFromString($input);
394 return $this->loadWithSource($Source);
395 }
396
397 private function loadWithSource($Source) {
398 if (empty ($Source)) return array();
399 if ($this->setting_use_syck_is_possible && function_exists ('syck_load')) {
400 $array = syck_load (implode ('', $Source));
401 return is_array($array) ? $array : array();
402 }
403
404 $this->path = array();
405 $this->result = array();
406
407 $cnt = count($Source);
408 for ($i = 0; $i < $cnt; $i++) {
409 $line = $Source[$i];
410
411 $this->indent = strlen($line) - strlen(ltrim($line));
412 $tempPath = $this->getParentPathByIndent($this->indent);
413 $line = self::stripIndent($line, $this->indent);
414 if (self::isComment($line)) continue;
415 if (self::isEmpty($line)) continue;
416 $this->path = $tempPath;
417
418 $literalBlockStyle = self::startsLiteralBlock($line);
419 if ($literalBlockStyle) {
420 $line = rtrim ($line, $literalBlockStyle . " \n");
421 $literalBlock = '';
422 $line .= $this->LiteralPlaceHolder;
423
424 while (++$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent)) {
425 $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
426 }
427 $i--;
428 }
429
430 while (++$i < $cnt && self::greedilyNeedNextLine($line)) {
431 $line = rtrim ($line, " \n\t\r") . ' ' . ltrim ($Source[$i], " \t");
432 }
433 $i--;
434
435
436
437 if (strpos ($line, '#')) {
438 if (strpos ($line, '"') === false && strpos ($line, "'") === false)
439 $line = preg_replace('/\s+#(.+)$/','',$line);
440 }
441
442 $lineArray = $this->_parseLine($line);
443
444 if ($literalBlockStyle)
445 $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
446
447 $this->addArray($lineArray, $this->indent);
448
449 foreach ($this->delayedPath as $indent => $delayedPath)
450 $this->path[$indent] = $delayedPath;
451
452 $this->delayedPath = array();
453
454 }
455 return $this->result;
456 }
457
458 private function loadFromSource ($input) {
459 if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
460 return file($input);
461
462 return $this->loadFromString($input);
463 }
464
465 private function loadFromString ($input) {
466 $lines = explode("\n",$input);
467 foreach ($lines as $k => $_) {
468 $lines[$k] = rtrim ($_, "\r");
469 }
470 return $lines;
471 }
472
473 /**
474 * Parses YAML code and returns an array for a node
475 * @access private
476 * @return array
477 * @param string $line A line from the YAML file
478 */
479 private function _parseLine($line) {
480 if (!$line) return array();
481 $line = trim($line);
482 if (!$line) return array();
483
484 $array = array();
485
486 $group = $this->nodeContainsGroup($line);
487 if ($group) {
488 $this->addGroup($line, $group);
489 $line = $this->stripGroup ($line, $group);
490 }
491
492 if ($this->startsMappedSequence($line))
493 return $this->returnMappedSequence($line);
494
495 if ($this->startsMappedValue($line))
496 return $this->returnMappedValue($line);
497
498 if ($this->isArrayElement($line))
499 return $this->returnArrayElement($line);
500
501 if ($this->isPlainArray($line))
502 return $this->returnPlainArray($line);
503
504
505 return $this->returnKeyValuePair($line);
506
507 }
508
509 /**
510 * Finds the type of the passed value, returns the value as the new type.
511 * @access private
512 * @param string $value
513 * @return mixed
514 */
515 private function _toType($value) {
516 if ($value === '') return null;
517 $first_character = $value[0];
518 $last_character = substr($value, -1, 1);
519
520 $is_quoted = false;
521 do {
522 if (!$value) break;
523 if ($first_character != '"' && $first_character != "'") break;
524 if ($last_character != '"' && $last_character != "'") break;
525 $is_quoted = true;
526 } while (0);
527
528 if ($is_quoted)
529 return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\'\'' => '\'', '\\\'' => '\''));
530
531 if (strpos($value, ' #') !== false && !$is_quoted)
532 $value = preg_replace('/\s+#(.+)$/','',$value);
533
534 if (!$is_quoted) $value = str_replace('\n', "\n", $value);
535
536 if ($first_character == '[' && $last_character == ']') {
537 // Take out strings sequences and mappings
538 $innerValue = trim(substr ($value, 1, -1));
539 if ($innerValue === '') return array();
540 $explode = $this->_inlineEscape($innerValue);
541 // Propagate value array
542 $value = array();
543 foreach ($explode as $v) {
544 $value[] = $this->_toType($v);
545 }
546 return $value;
547 }
548
549 if (strpos($value,': ')!==false && $first_character != '{') {
550 $array = explode(': ',$value);
551 $key = trim($array[0]);
552 array_shift($array);
553 $value = trim(implode(': ',$array));
554 $value = $this->_toType($value);
555 return array($key => $value);
556 }
557
558 if ($first_character == '{' && $last_character == '}') {
559 $innerValue = trim(substr ($value, 1, -1));
560 if ($innerValue === '') return array();
561 // Inline Mapping
562 // Take out strings sequences and mappings
563 $explode = $this->_inlineEscape($innerValue);
564 // Propagate value array
565 $array = array();
566 foreach ($explode as $v) {
567 $SubArr = $this->_toType($v);
568 if (empty($SubArr)) continue;
569 if (is_array ($SubArr)) {
570 $array[key($SubArr)] = $SubArr[key($SubArr)]; continue;
571 }
572 $array[] = $SubArr;
573 }
574 return $array;
575 }
576
577 if ($value == 'null' || $value == 'NULL' || $value == 'Null' || $value == '' || $value == '~') {
578 return null;
579 }
580
581 if (intval($first_character) > 0 && preg_match ('/^[1-9]+[0-9]*$/', $value)) {
582 $intvalue = (int)$value;
583 if ($intvalue != PHP_INT_MAX)
584 $value = $intvalue;
585 return $value;
586 }
587
588 if (in_array($value,
589 array('true', 'on', '+', 'yes', 'y', 'True', 'TRUE', 'On', 'ON', 'YES', 'Yes', 'Y'))) {
590 return true;
591 }
592
593 if (in_array(strtolower($value),
594 array('false', 'off', '-', 'no', 'n'))) {
595 return false;
596 }
597
598 if (is_numeric($value)) {
599 if ($value === '0') return 0;
600 if (trim ($value, 0) === $value)
601 $value = (float)$value;
602 return $value;
603 }
604
605 return $value;
606 }
607
608 /**
609 * Used in inlines to check for more inlines or quoted strings
610 * @access private
611 * @return array
612 */
613 private function _inlineEscape($inline) {
614 // There's gotta be a cleaner way to do this...
615 // While pure sequences seem to be nesting just fine,
616 // pure mappings and mappings with sequences inside can't go very
617 // deep. This needs to be fixed.
618
619 $seqs = array();
620 $maps = array();
621 $saved_strings = array();
622
623 // Check for strings
624 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
625 if (preg_match_all($regex,$inline,$strings)) {
626 $saved_strings = $strings[0];
627 $inline = preg_replace($regex,'YAMLString',$inline);
628 }
629 unset($regex);
630
631 $i = 0;
632 do {
633
634 // Check for sequences
635 while (preg_match('/\[([^{}\[\]]+)\]/U',$inline,$matchseqs)) {
636 $seqs[] = $matchseqs[0];
637 $inline = preg_replace('/\[([^{}\[\]]+)\]/U', ('YAMLSeq' . (count($seqs) - 1) . 's'), $inline, 1);
638 }
639
640 // Check for mappings
641 while (preg_match('/{([^\[\]{}]+)}/U',$inline,$matchmaps)) {
642 $maps[] = $matchmaps[0];
643 $inline = preg_replace('/{([^\[\]{}]+)}/U', ('YAMLMap' . (count($maps) - 1) . 's'), $inline, 1);
644 }
645
646 if ($i++ >= 10) break;
647
648 } while (strpos ($inline, '[') !== false || strpos ($inline, '{') !== false);
649
650 $explode = explode(', ',$inline);
651 $stringi = 0; $i = 0;
652
653 while (1) {
654
655 // Re-add the sequences
656 if (!empty($seqs)) {
657 foreach ($explode as $key => $value) {
658 if (strpos($value,'YAMLSeq') !== false) {
659 foreach ($seqs as $seqk => $seq) {
660 $explode[$key] = str_replace(('YAMLSeq'.$seqk.'s'),$seq,$value);
661 $value = $explode[$key];
662 }
663 }
664 }
665 }
666
667 // Re-add the mappings
668 if (!empty($maps)) {
669 foreach ($explode as $key => $value) {
670 if (strpos($value,'YAMLMap') !== false) {
671 foreach ($maps as $mapk => $map) {
672 $explode[$key] = str_replace(('YAMLMap'.$mapk.'s'), $map, $value);
673 $value = $explode[$key];
674 }
675 }
676 }
677 }
678
679
680 // Re-add the strings
681 if (!empty($saved_strings)) {
682 foreach ($explode as $key => $value) {
683 while (strpos($value,'YAMLString') !== false) {
684 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$stringi],$value, 1);
685 unset($saved_strings[$stringi]);
686 ++$stringi;
687 $value = $explode[$key];
688 }
689 }
690 }
691
692 $finished = true;
693 foreach ($explode as $key => $value) {
694 if (strpos($value,'YAMLSeq') !== false) {
695 $finished = false; break;
696 }
697 if (strpos($value,'YAMLMap') !== false) {
698 $finished = false; break;
699 }
700 if (strpos($value,'YAMLString') !== false) {
701 $finished = false; break;
702 }
703 }
704 if ($finished) break;
705
706 $i++;
707 if ($i > 10)
708 break; // Prevent infinite loops.
709 }
710
711 return $explode;
712 }
713
714 private function literalBlockContinues ($line, $lineIndent) {
715 if (!trim($line)) return true;
716 if (strlen($line) - strlen(ltrim($line)) > $lineIndent) return true;
717 return false;
718 }
719
720 private function referenceContentsByAlias ($alias) {
721 do {
722 if (!isset($this->SavedGroups[$alias])) { echo "Bad group name: $alias."; break; }
723 $groupPath = $this->SavedGroups[$alias];
724 $value = $this->result;
725 foreach ($groupPath as $k) {
726 $value = $value[$k];
727 }
728 } while (false);
729 return $value;
730 }
731
732 private function addArrayInline ($array, $indent) {
733 $CommonGroupPath = $this->path;
734 if (empty ($array)) return false;
735
736 foreach ($array as $k => $_) {
737 $this->addArray(array($k => $_), $indent);
738 $this->path = $CommonGroupPath;
739 }
740 return true;
741 }
742
743 private function addArray ($incoming_data, $incoming_indent) {
744
745 // print_r ($incoming_data);
746
747 if (count ($incoming_data) > 1)
748 return $this->addArrayInline ($incoming_data, $incoming_indent);
749
750 $key = key ($incoming_data);
751 $value = isset($incoming_data[$key]) ? $incoming_data[$key] : null;
752 if ($key === '__!YAMLZero') $key = '0';
753
754 if ($incoming_indent == 0 && !$this->_containsGroupAlias && !$this->_containsGroupAnchor) { // Shortcut for root-level values.
755 if ($key || $key === '' || $key === '0') {
756 $this->result[$key] = $value;
757 } else {
758 $this->result[] = $value; end ($this->result); $key = key ($this->result);
759 }
760 $this->path[$incoming_indent] = $key;
761 return;
762 }
763
764
765
766 $history = array();
767 // Unfolding inner array tree.
768 $history[] = $_arr = $this->result;
769 foreach ($this->path as $k) {
770 $history[] = $_arr = $_arr[$k];
771 }
772
773 if ($this->_containsGroupAlias) {
774 $value = $this->referenceContentsByAlias($this->_containsGroupAlias);
775 $this->_containsGroupAlias = false;
776 }
777
778
779 // Adding string or numeric key to the innermost level or $this->arr.
780 if (is_string($key) && $key == '<<') {
781 if (!is_array ($_arr)) { $_arr = array (); }
782
783 $_arr = array_merge ($_arr, $value);
784 } else if ($key || $key === '' || $key === '0') {
785 $_arr[$key] = $value;
786 } else {
787 if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
788 else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
789 }
790
791 $reverse_path = array_reverse($this->path);
792 $reverse_history = array_reverse ($history);
793 $reverse_history[0] = $_arr;
794 $cnt = count($reverse_history) - 1;
795 for ($i = 0; $i < $cnt; $i++) {
796 $reverse_history[$i+1][$reverse_path[$i]] = $reverse_history[$i];
797 }
798 $this->result = $reverse_history[$cnt];
799
800 $this->path[$incoming_indent] = $key;
801
802 if ($this->_containsGroupAnchor) {
803 $this->SavedGroups[$this->_containsGroupAnchor] = $this->path;
804 if (is_array ($value)) {
805 $k = key ($value);
806 if (!is_int ($k)) {
807 $this->SavedGroups[$this->_containsGroupAnchor][$incoming_indent + 2] = $k;
808 }
809 }
810 $this->_containsGroupAnchor = false;
811 }
812
813 }
814
815 private static function startsLiteralBlock ($line) {
816 $lastChar = substr (trim($line), -1);
817 if ($lastChar != '>' && $lastChar != '|') return false;
818 if ($lastChar == '|') return $lastChar;
819 // HTML tags should not be counted as literal blocks.
820 if (preg_match ('#<.*?>$#', $line)) return false;
821 return $lastChar;
822 }
823
824 private static function greedilyNeedNextLine($line) {
825 $line = trim ($line);
826 if (!strlen($line)) return false;
827 if (substr ($line, -1, 1) == ']') return false;
828 if ($line[0] == '[') return true;
829 if (preg_match ('#^[^:]+?:\s*\[#', $line)) return true;
830 return false;
831 }
832
833 private function addLiteralLine ($literalBlock, $line, $literalBlockStyle) {
834 $line = self::stripIndent($line);
835 $line = rtrim ($line, "\r\n\t ") . "\n";
836 if ($literalBlockStyle == '|') {
837 return $literalBlock . $line;
838 }
839 if (strlen($line) == 0)
840 return rtrim($literalBlock, ' ') . "\n";
841 if ($line == "\n" && $literalBlockStyle == '>') {
842 return rtrim ($literalBlock, " \t") . "\n";
843 }
844 if ($line != "\n")
845 $line = trim ($line, "\r\n ") . " ";
846 return $literalBlock . $line;
847 }
848
849 function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
850 foreach ($lineArray as $k => $_) {
851 if (is_array($_))
852 $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
853 else if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder)
854 $lineArray[$k] = rtrim ($literalBlock, " \r\n");
855 }
856 return $lineArray;
857 }
858
859 private static function stripIndent ($line, $indent = -1) {
860 if ($indent == -1) $indent = strlen($line) - strlen(ltrim($line));
861 return substr ($line, $indent);
862 }
863
864 private function getParentPathByIndent ($indent) {
865 if ($indent == 0) return array();
866 $linePath = $this->path;
867 do {
868 end($linePath); $lastIndentInParentPath = key($linePath);
869 if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
870 } while ($indent <= $lastIndentInParentPath);
871 return $linePath;
872 }
873
874
875 private function clearBiggerPathValues ($indent) {
876
877
878 if ($indent == 0) $this->path = array();
879 if (empty ($this->path)) return true;
880
881 foreach ($this->path as $k => $_) {
882 if ($k > $indent) unset ($this->path[$k]);
883 }
884
885 return true;
886 }
887
888
889 private static function isComment ($line) {
890 if (!$line) return false;
891 if ($line[0] == '#') return true;
892 if (trim($line, " \r\n\t") == '---') return true;
893 return false;
894 }
895
896 private static function isEmpty ($line) {
897 return (trim ($line) === '');
898 }
899
900
901 private function isArrayElement ($line) {
902 if (!$line) return false;
903 if ($line[0] != '-') return false;
904 if (strlen ($line) > 3)
905 if (substr($line,0,3) == '---') return false;
906
907 return true;
908 }
909
910 private function isHashElement ($line) {
911 return strpos($line, ':');
912 }
913
914 private function isLiteral ($line) {
915 if ($this->isArrayElement($line)) return false;
916 if ($this->isHashElement($line)) return false;
917 return true;
918 }
919
920
921 private static function unquote ($value) {
922 if (!$value) return $value;
923 if (!is_string($value)) return $value;
924 if ($value[0] == '\'') return trim ($value, '\'');
925 if ($value[0] == '"') return trim ($value, '"');
926 return $value;
927 }
928
929 private function startsMappedSequence ($line) {
930 return ($line[0] == '-' && substr ($line, -1, 1) == ':');
931 }
932
933 private function returnMappedSequence ($line) {
934 $array = array();
935 $key = self::unquote(trim(substr($line,1,-1)));
936 $array[$key] = array();
937 $this->delayedPath = array(strpos ($line, $key) + $this->indent => $key);
938 return array($array);
939 }
940
941 private function returnMappedValue ($line) {
942 $array = array();
943 $key = self::unquote (trim(substr($line,0,-1)));
944 $array[$key] = '';
945 return $array;
946 }
947
948 private function startsMappedValue ($line) {
949 return (substr ($line, -1, 1) == ':');
950 }
951
952 private function isPlainArray ($line) {
953 return ($line[0] == '[' && substr ($line, -1, 1) == ']');
954 }
955
956 private function returnPlainArray ($line) {
957 return $this->_toType($line);
958 }
959
960 private function returnKeyValuePair ($line) {
961 $array = array();
962 $key = '';
963 if (strpos ($line, ':')) {
964 // It's a key/value pair most likely
965 // If the key is in double quotes pull it out
966 if (($line[0] == '"' || $line[0] == "'") && preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
967 $value = trim(str_replace($matches[1],'',$line));
968 $key = $matches[2];
969 } else {
970 // Do some guesswork as to the key and the value
971 $explode = explode(':',$line);
972 $key = trim($explode[0]);
973 array_shift($explode);
974 $value = trim(implode(':',$explode));
975 }
976 // Set the type of the value. Int, string, etc
977 $value = $this->_toType($value);
978 if ($key === '0') $key = '__!YAMLZero';
979 $array[$key] = $value;
980 } else {
981 $array = array ($line);
982 }
983 return $array;
984
985 }
986
987
988 private function returnArrayElement ($line) {
989 if (strlen($line) <= 1) return array(array()); // Weird %)
990 $array = array();
991 $value = trim(substr($line,1));
992 $value = $this->_toType($value);
993 $array[] = $value;
994 return $array;
995 }
996
997
998 private function nodeContainsGroup ($line) {
999 $symbolsForReference = 'A-z0-9_\-';
1000 if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
1001 if ($line[0] == '&' && preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
1002 if ($line[0] == '*' && preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
1003 if (preg_match('/(&['.$symbolsForReference.']+)$/', $line, $matches)) return $matches[1];
1004 if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
1005 if (preg_match ('#^\s*<<\s*:\s*(\*[^\s]+).*$#', $line, $matches)) return $matches[1];
1006 return false;
1007
1008 }
1009
1010 private function addGroup ($line, $group) {
1011 if ($group[0] == '&') $this->_containsGroupAnchor = substr ($group, 1);
1012 if ($group[0] == '*') $this->_containsGroupAlias = substr ($group, 1);
1013 //print_r ($this->path);
1014 }
1015
1016 private function stripGroup ($line, $group) {
1017 $line = trim(str_replace($group, '', $line));
1018 return $line;
1019 }
1020 }
1021
1022 // Enable use of Spyc from command line
1023 // The syntax is the following: php spyc.php spyc.yaml
1024
1025 define ('SPYC_FROM_COMMAND_LINE', false);
1026
1027 do {
1028 if (!SPYC_FROM_COMMAND_LINE) break;
1029 if (empty ($_SERVER['argc']) || $_SERVER['argc'] < 2) break;
1030 if (empty ($_SERVER['PHP_SELF']) || $_SERVER['PHP_SELF'] != 'spyc.php') break;
1031 $file = $argv[1];
1032 printf ("Spyc loading file: %s\n", $file);
1033 print_r (spyc_load_file ($file));
1034 } while (0);