Changes in changes (hm..)
[spyc.git] / spyc.php4
blobdc5a771c11c45817ffee7c1b5b27a83f604112ca
1 <?php
2 /**
3 * Spyc -- A Simple PHP YAML Class
4 * @version 0.3
5 * @author Chris Wanstrath <chris@ozmm.org>
6 * @author Vlad Andersen <vlad@oneiros.ru>
7 * @link http://spyc.sourceforge.net/
8 * @copyright Copyright 2005-2006 Chris Wanstrath
9 * @license http://www.opensource.org/licenses/mit-license.php MIT License
10 * @package Spyc
12 /**
13 * The Simple PHP YAML Class.
15 * This class can be used to read a YAML file and convert its contents
16 * into a PHP array. It currently supports a very limited subsection of
17 * the YAML spec.
19 * Usage:
20 * <code>
21 * $parser = new Spyc;
22 * $array = $parser->load($file);
23 * </code>
24 * @package Spyc
26 class Spyc {
28 /**#@+
29 * @access private
30 * @var mixed
32 var $_haveRefs;
33 var $_allNodes;
34 var $_allParent;
35 var $_lastIndent;
36 var $_lastNode;
37 var $_inBlock;
38 var $_isInline;
39 var $_dumpIndent;
40 var $_dumpWordWrap;
41 var $_containsGroupAnchor = false;
42 var $_containsGroupAlias = false;
43 var $path;
44 var $result;
45 var $LiteralBlockMarkers = array ('>', '|');
46 var $LiteralPlaceHolder = '___YAML_Literal_Block___';
47 var $SavedGroups = array();
49 /**#@+
50 * @access public
51 * @var mixed
53 var $_nodeId;
55 /**
56 * Load YAML into a PHP array statically
58 * The load method, when supplied with a YAML stream (string or file),
59 * will do its best to convert YAML in a file into a PHP array. Pretty
60 * simple.
61 * Usage:
62 * <code>
63 * $array = Spyc::YAMLLoad('lucky.yaml');
64 * print_r($array);
65 * </code>
66 * @access public
67 * @return array
68 * @param string $input Path of YAML file or string containing YAML
70 function YAMLLoad($input) {
71 $Spyc = new Spyc;
72 return $Spyc->load($input);
75 /**
76 * Dump YAML from PHP array statically
78 * The dump method, when supplied with an array, will do its best
79 * to convert the array into friendly YAML. Pretty simple. Feel free to
80 * save the returned string as nothing.yaml and pass it around.
82 * Oh, and you can decide how big the indent is and what the wordwrap
83 * for folding is. Pretty cool -- just pass in 'false' for either if
84 * you want to use the default.
86 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
87 * you can turn off wordwrap by passing in 0.
89 * @access public
90 * @return string
91 * @param array $array PHP array
92 * @param int $indent Pass in false to use the default, which is 2
93 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
95 function YAMLDump($array,$indent = false,$wordwrap = false) {
96 $spyc = new Spyc;
97 return $spyc->dump($array,$indent,$wordwrap);
102 * Dump PHP array to YAML
104 * The dump method, when supplied with an array, will do its best
105 * to convert the array into friendly YAML. Pretty simple. Feel free to
106 * save the returned string as tasteful.yaml and pass it around.
108 * Oh, and you can decide how big the indent is and what the wordwrap
109 * for folding is. Pretty cool -- just pass in 'false' for either if
110 * you want to use the default.
112 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
113 * you can turn off wordwrap by passing in 0.
115 * @access public
116 * @return string
117 * @param array $array PHP array
118 * @param int $indent Pass in false to use the default, which is 2
119 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
121 function dump($array,$indent = false,$wordwrap = false) {
122 // Dumps to some very clean YAML. We'll have to add some more features
123 // and options soon. And better support for folding.
125 // New features and options.
126 if ($indent === false or !is_numeric($indent)) {
127 $this->_dumpIndent = 2;
128 } else {
129 $this->_dumpIndent = $indent;
132 if ($wordwrap === false or !is_numeric($wordwrap)) {
133 $this->_dumpWordWrap = 40;
134 } else {
135 $this->_dumpWordWrap = $wordwrap;
138 // New YAML document
139 $string = "---\n";
141 // Start at the base of the array and move through it.
142 foreach ($array as $key => $value) {
143 $string .= $this->_yamlize($key,$value,0);
145 return $string;
149 * Attempts to convert a key / value array item to YAML
150 * @access private
151 * @return string
152 * @param $key The name of the key
153 * @param $value The value of the item
154 * @param $indent The indent of the current node
156 function _yamlize($key,$value,$indent) {
157 if (is_array($value)) {
158 // It has children. What to do?
159 // Make it the right kind of item
160 $string = $this->_dumpNode($key,NULL,$indent);
161 // Add the indent
162 $indent += $this->_dumpIndent;
163 // Yamlize the array
164 $string .= $this->_yamlizeArray($value,$indent);
165 } elseif (!is_array($value)) {
166 // It doesn't have children. Yip.
167 $string = $this->_dumpNode($key,$value,$indent);
169 return $string;
173 * Attempts to convert an array to YAML
174 * @access private
175 * @return string
176 * @param $array The array you want to convert
177 * @param $indent The indent of the current level
179 function _yamlizeArray($array,$indent) {
180 if (is_array($array)) {
181 $string = '';
182 foreach ($array as $key => $value) {
183 $string .= $this->_yamlize($key,$value,$indent);
185 return $string;
186 } else {
187 return false;
192 * Returns YAML from a key and a value
193 * @access private
194 * @return string
195 * @param $key The name of the key
196 * @param $value The value of the item
197 * @param $indent The indent of the current node
199 function _dumpNode($key,$value,$indent) {
200 // do some folding here, for blocks
201 if (strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false) {
202 $value = $this->_doLiteralBlock($value,$indent);
203 } else {
204 $value = $this->_doFolding($value,$indent);
207 if (is_bool($value)) {
208 $value = ($value) ? "true" : "false";
211 $spaces = str_repeat(' ',$indent);
213 if (is_int($key)) {
214 // It's a sequence
215 $string = $spaces.'- '.$value."\n";
216 } else {
217 // It's mapped
218 if (strpos($key, ":") !== false) { $key = '"' . $key . '"'; }
219 $string = $spaces.$key.': '.$value."\n";
221 return $string;
225 * Creates a literal block for dumping
226 * @access private
227 * @return string
228 * @param $value
229 * @param $indent int The value of the indent
231 function _doLiteralBlock($value,$indent) {
232 $exploded = explode("\n",$value);
233 $newValue = '|';
234 $indent += $this->_dumpIndent;
235 $spaces = str_repeat(' ',$indent);
236 foreach ($exploded as $line) {
237 $newValue .= "\n" . $spaces . trim($line);
239 return $newValue;
243 * Folds a string of text, if necessary
244 * @access private
245 * @return string
246 * @param $value The string you wish to fold
248 function _doFolding($value,$indent) {
249 // Don't do anything if wordwrap is set to 0
250 if ($this->_dumpWordWrap === 0) {
251 return $value;
254 if (strlen($value) > $this->_dumpWordWrap) {
255 $indent += $this->_dumpIndent;
256 $indent = str_repeat(' ',$indent);
257 $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
258 $value = ">\n".$indent.$wrapped;
260 return $value;
263 /* LOADING FUNCTIONS */
265 function load($input) {
266 $Source = $this->loadFromSource($input);
267 if (empty ($Source)) return array();
268 $this->path = array();
269 $this->result = array();
272 for ($i = 0; $i < count($Source); $i++) {
273 $line = $Source[$i];
274 $lineIndent = $this->_getIndent($line);
275 $this->path = $this->getParentPathByIndent($lineIndent);
276 $line = $this->stripIndent($line, $lineIndent);
277 if ($this->isComment($line)) continue;
279 if ($literalBlockStyle = $this->startsLiteralBlock($line)) {
280 $line = rtrim ($line, $literalBlockStyle . "\n");
281 $literalBlock = '';
282 $line .= $this->LiteralPlaceHolder;
284 while (++$i < count($Source) && $this->literalBlockContinues($Source[$i], $lineIndent)) {
285 $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
287 $i--;
289 $lineArray = $this->_parseLine($line);
291 if ($literalBlockStyle)
292 $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
294 $this->addArray($lineArray, $lineIndent);
296 return $this->result;
299 function loadFromSource ($input) {
300 if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
301 return file($input);
303 $foo = explode("\n",$input);
304 foreach ($foo as $k => $_) {
305 $foo[$k] = trim ($_, "\r");
307 return $foo;
311 * Finds and returns the indentation of a YAML line
312 * @access private
313 * @return int
314 * @param string $line A line from the YAML file
316 function _getIndent($line) {
317 if (!preg_match('/^ +/',$line,$match)) return 0;
318 if (!empty($match[0])) return strlen ($match[0]);
319 return 0;
323 * Parses YAML code and returns an array for a node
324 * @access private
325 * @return array
326 * @param string $line A line from the YAML file
328 function _parseLine($line) {
329 if (!$line) return array();
330 $line = trim($line);
331 if (!$line) return array();
332 $array = array();
334 if ($group = $this->nodeContainsGroup($line)) {
335 $this->addGroup($line, $group);
336 $line = $this->stripGroup ($line, $group);
339 if ($this->startsMappedSequence($line))
340 return $this->returnMappedSequence($line);
342 if ($this->startsMappedValue($line))
343 return $this->returnMappedValue($line);
345 if ($this->isArrayElement($line))
346 return $this->returnArrayElement($line);
348 if ($this->isPlainArray($line))
349 return $this->returnPlainArray($line);
351 return $this->returnKeyValuePair($line);
358 * Finds the type of the passed value, returns the value as the new type.
359 * @access private
360 * @param string $value
361 * @return mixed
363 function _toType($value) {
365 if (strpos($value, '#') !== false)
366 $value = trim(preg_replace('/#(.+)$/','',$value));
368 if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
369 $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
370 $value = preg_replace('/\\\\"/','"',$value);
371 } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
372 // Inline Sequence
374 // Take out strings sequences and mappings
375 $explode = $this->_inlineEscape($matches[1]);
377 // Propagate value array
378 $value = array();
379 foreach ($explode as $v) {
380 $value[] = $this->_toType($v);
382 } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
383 // It's a map
384 $array = explode(': ',$value);
385 $key = trim($array[0]);
386 array_shift($array);
387 $value = trim(implode(': ',$array));
388 $value = $this->_toType($value);
389 $value = array($key => $value);
390 } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
391 // Inline Mapping
393 // Take out strings sequences and mappings
394 $explode = $this->_inlineEscape($matches[1]);
396 // Propogate value array
397 $array = array();
398 foreach ($explode as $v) {
399 $SubArr = $this->_toType($v);
400 if (empty($SubArr)) continue;
401 if (is_array ($SubArr)) {
402 $array[key($SubArr)] = $SubArr[key($SubArr)]; continue;
404 $array[] = $SubArr;
406 $value = $array;
407 } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
408 $value = null;
409 } elseif (preg_match ('/^[0-9]+$/', $value)) {
410 $value = (int)$value;
411 } elseif (in_array(strtolower($value),
412 array('true', 'on', '+', 'yes', 'y'))) {
413 $value = true;
414 } elseif (in_array(strtolower($value),
415 array('false', 'off', '-', 'no', 'n'))) {
416 $value = false;
417 } elseif (is_numeric($value)) {
418 $value = (float)$value;
419 } else {
420 // Just a normal string, right?
425 // print_r ($value);
426 return $value;
430 * Used in inlines to check for more inlines or quoted strings
431 * @access private
432 * @return array
434 function _inlineEscape($inline) {
435 // There's gotta be a cleaner way to do this...
436 // While pure sequences seem to be nesting just fine,
437 // pure mappings and mappings with sequences inside can't go very
438 // deep. This needs to be fixed.
440 $saved_strings = array();
442 // Check for strings
443 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
444 if (preg_match_all($regex,$inline,$strings)) {
445 $saved_strings = $strings[0];
446 $inline = preg_replace($regex,'YAMLString',$inline);
448 unset($regex);
450 // Check for sequences
451 if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
452 $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
453 $seqs = $seqs[0];
456 // Check for mappings
457 if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
458 $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
459 $maps = $maps[0];
462 $explode = explode(', ',$inline);
465 // Re-add the sequences
466 if (!empty($seqs)) {
467 $i = 0;
468 foreach ($explode as $key => $value) {
469 if (strpos($value,'YAMLSeq') !== false) {
470 $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
471 ++$i;
476 // Re-add the mappings
477 if (!empty($maps)) {
478 $i = 0;
479 foreach ($explode as $key => $value) {
480 if (strpos($value,'YAMLMap') !== false) {
481 $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
482 ++$i;
488 // Re-add the strings
489 if (!empty($saved_strings)) {
490 $i = 0;
491 foreach ($explode as $key => $value) {
492 while (strpos($value,'YAMLString') !== false) {
493 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
494 ++$i;
495 $value = $explode[$key];
500 return $explode;
503 function literalBlockContinues ($line, $lineIndent) {
504 if (!trim($line)) return true;
505 if ($this->_getIndent($line) > $lineIndent) return true;
506 return false;
509 function addArrayInline ($array, $indent) {
510 $CommonGroupPath = $this->path;
511 if (empty ($array)) return false;
513 foreach ($array as $k => $_) {
514 $this->addArray(array($k => $_), $indent);
515 $this->path = $CommonGroupPath;
517 return true;
520 function addArray ($array, $indent) {
521 if (count ($array) > 1)
522 return $this->addArrayInline ($array, $indent);
525 $key = key ($array);
526 if (!isset ($array[$key])) return false;
527 if ($array[$key] === array()) { $array[$key] = ''; };
528 $value = $array[$key];
530 // Unfolding inner array tree as defined in $this->_arrpath.
531 //$_arr = $this->result; $_tree[0] = $_arr; $i = 1;
533 $tempPath = Spyc::flatten ($this->path);
534 eval ('$_arr = $this->result' . $tempPath . ';');
537 if ($this->_containsGroupAlias) {
538 do {
539 if (!isset($this->SavedGroups[$this->_containsGroupAlias])) { echo "Bad group name: $this->_containsGroupAlias."; break; }
540 $groupPath = $this->SavedGroups[$this->_containsGroupAlias];
541 eval ('$value = $this->result' . Spyc::flatten ($groupPath) . ';');
542 } while (false);
543 $this->_containsGroupAlias = false;
547 // Adding string or numeric key to the innermost level or $this->arr.
548 if ($key)
549 $_arr[$key] = $value;
550 else {
551 if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
552 else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
556 $this->path[$indent] = $key;
558 eval ('$this->result' . $tempPath . ' = $_arr;');
560 if ($this->_containsGroupAnchor) {
561 $this->SavedGroups[$this->_containsGroupAnchor] = $this->path;
562 $this->_containsGroupAnchor = false;
569 function flatten ($array) {
570 $tempPath = array();
571 if (!empty ($array)) {
572 foreach ($array as $_) {
573 if (!is_int($_)) $_ = "'$_'";
574 $tempPath[] = "[$_]";
577 //end ($tempPath); $latestKey = key($tempPath);
578 $tempPath = implode ('', $tempPath);
579 return $tempPath;
584 function startsLiteralBlock ($line) {
585 $lastChar = substr (trim($line), -1);
586 if (in_array ($lastChar, $this->LiteralBlockMarkers))
587 return $lastChar;
588 return false;
591 function addLiteralLine ($literalBlock, $line, $literalBlockStyle) {
592 $line = $this->stripIndent($line);
593 $line = str_replace ("\r\n", "\n", $line);
595 if ($literalBlockStyle == '|') {
596 return $literalBlock . $line;
598 if (strlen($line) == 0) return $literalBlock . "\n";
600 // echo "|$line|";
601 if ($line != "\n")
602 $line = trim ($line, "\r\n ") . " ";
604 return $literalBlock . $line;
607 function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
609 foreach ($lineArray as $k => $_) {
610 if (is_array($_))
611 $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
612 else{
613 if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder)
614 $lineArray[$k] = rtrim ($literalBlock, " \r\n");
617 return $lineArray;
620 function stripIndent ($line, $indent = -1) {
621 if ($indent == -1) $indent = $this->_getIndent($line);
622 return substr ($line, $indent);
625 function getParentPathByIndent ($indent) {
627 if ($indent == 0) return array();
629 $linePath = $this->path;
630 do {
631 end($linePath); $lastIndentInParentPath = key($linePath);
632 if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
633 } while ($indent <= $lastIndentInParentPath);
634 return $linePath;
638 function clearBiggerPathValues ($indent) {
641 if ($indent == 0) $this->path = array();
642 if (empty ($this->path)) return true;
644 foreach ($this->path as $k => $_) {
645 if ($k > $indent) unset ($this->path[$k]);
648 return true;
652 function isComment ($line) {
653 if (preg_match('/^#/', $line)) return true;
654 if (trim($line, " \r\n\t") == '---') return true;
655 return false;
658 function isArrayElement ($line) {
659 if (!$line) return false;
660 if ($line[0] != '-') return false;
661 if (strlen ($line) > 3)
662 if (substr($line,0,3) == '---') return false;
664 return true;
667 function isHashElement ($line) {
668 if (!preg_match('/^(.+?):/', $line, $matches)) return false;
669 $allegedKey = $matches[1];
670 if ($allegedKey) return true;
671 //if (substr_count($allegedKey, )
672 return false;
675 function isLiteral ($line) {
676 if ($this->isArrayElement($line)) return false;
677 if ($this->isHashElement($line)) return false;
678 return true;
682 function startsMappedSequence ($line) {
683 if (preg_match('/^-(.*):$/',$line)) return true;
686 function returnMappedSequence ($line) {
687 $array = array();
688 $key = trim(substr(substr($line,1),0,-1));
689 $array[$key] = '';
690 return $array;
693 function returnMappedValue ($line) {
694 $array = array();
695 $key = trim(substr($line,0,-1));
696 $array[$key] = '';
697 return $array;
700 function startsMappedValue ($line) {
701 if (preg_match('/^(.*):$/',$line)) return true;
704 function isPlainArray ($line) {
705 if (preg_match('/^\[(.*)\]$/', $line)) return true;
706 return false;
709 function returnPlainArray ($line) {
710 return $this->_toType($line);
713 function returnKeyValuePair ($line) {
715 $array = array();
717 if (preg_match('/^(.+):/',$line,$key)) {
718 // It's a key/value pair most likely
719 // If the key is in double quotes pull it out
720 if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
721 $value = trim(str_replace($matches[1],'',$line));
722 $key = $matches[2];
723 } else {
724 // Do some guesswork as to the key and the value
725 $explode = explode(':',$line);
726 $key = trim($explode[0]);
727 array_shift($explode);
728 $value = trim(implode(':',$explode));
731 // Set the type of the value. Int, string, etc
732 $value = $this->_toType($value);
733 if (empty($key)) {
734 $array[] = $value;
735 } else {
736 $array[$key] = $value;
740 return $array;
745 function returnArrayElement ($line) {
746 if (strlen($line) <= 1) return array(array()); // Weird %)
747 $array = array();
748 $value = trim(substr($line,1));
749 $value = $this->_toType($value);
750 $array[] = $value;
751 return $array;
755 function nodeContainsGroup ($line) {
756 $symbolsForReference = 'A-z0-9_\-';
757 if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
758 if (preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
759 if (preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
760 if (preg_match('/(&['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
761 if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
762 return false;
765 function addGroup ($line, $group) {
766 if (substr ($group, 0, 1) == '&') $this->_containsGroupAnchor = substr ($group, 1);
767 if (substr ($group, 0, 1) == '*') $this->_containsGroupAlias = substr ($group, 1);
768 //print_r ($this->path);
771 function stripGroup ($line, $group) {
772 $line = trim(str_replace($group, '', $line));
773 return $line;