3 * Spyc -- A Simple PHP YAML Class
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
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
22 * $array = $parser->load($file);
41 var $_containsGroupAnchor = false;
42 var $_containsGroupAlias = false;
45 var $LiteralBlockMarkers = array ('>', '|');
46 var $LiteralPlaceHolder = '___YAML_Literal_Block___';
47 var $SavedGroups = array();
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
63 * $array = Spyc::YAMLLoad('lucky.yaml');
68 * @param string $input Path of YAML file or string containing YAML
70 function YAMLLoad($input) {
72 return $Spyc->load($input);
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.
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) {
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.
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;
129 $this->_dumpIndent
= $indent;
132 if ($wordwrap === false or !is_numeric($wordwrap)) {
133 $this->_dumpWordWrap
= 40;
135 $this->_dumpWordWrap
= $wordwrap;
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);
149 * Attempts to convert a key / value array item to YAML
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);
162 $indent +
= $this->_dumpIndent
;
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);
173 * Attempts to convert an array to YAML
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)) {
182 foreach ($array as $key => $value) {
183 $string .= $this->_yamlize($key,$value,$indent);
192 * Returns YAML from a key and a value
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);
204 $value = $this->_doFolding($value,$indent);
207 if (is_bool($value)) {
208 $value = ($value) ?
"true" : "false";
211 $spaces = str_repeat(' ',$indent);
215 $string = $spaces.'- '.$value."\n";
218 if (strpos($key, ":") !== false) { $key = '"' . $key . '"'; }
219 $string = $spaces.$key.': '.$value."\n";
225 * Creates a literal block for dumping
229 * @param $indent int The value of the indent
231 function _doLiteralBlock($value,$indent) {
232 $exploded = explode("\n",$value);
234 $indent +
= $this->_dumpIndent
;
235 $spaces = str_repeat(' ',$indent);
236 foreach ($exploded as $line) {
237 $newValue .= "\n" . $spaces . trim($line);
243 * Folds a string of text, if necessary
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) {
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;
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++
) {
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");
282 $line .= $this->LiteralPlaceHolder
;
284 while (++
$i < count($Source) && $this->literalBlockContinues($Source[$i], $lineIndent)) {
285 $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
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))
303 $foo = explode("\n",$input);
304 foreach ($foo as $k => $_) {
305 $foo[$k] = trim ($_, "\r");
311 * Finds and returns the indentation of a YAML line
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]);
323 * Parses YAML code and returns an array for a node
326 * @param string $line A line from the YAML file
328 function _parseLine($line) {
329 if (!$line) return array();
331 if (!$line) return 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.
360 * @param string $value
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)) {
374 // Take out strings sequences and mappings
375 $explode = $this->_inlineEscape($matches[1]);
377 // Propagate value array
379 foreach ($explode as $v) {
380 $value[] = $this->_toType($v);
382 } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
384 $array = explode(': ',$value);
385 $key = trim($array[0]);
387 $value = trim(implode(': ',$array));
388 $value = $this->_toType($value);
389 $value = array($key => $value);
390 } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
393 // Take out strings sequences and mappings
394 $explode = $this->_inlineEscape($matches[1]);
396 // Propogate value 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;
407 } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
409 } elseif (preg_match ('/^[0-9]+$/', $value)) {
410 $value = (int)$value;
411 } elseif (in_array(strtolower($value),
412 array('true', 'on', '+', 'yes', 'y'))) {
414 } elseif (in_array(strtolower($value),
415 array('false', 'off', '-', 'no', 'n'))) {
417 } elseif (is_numeric($value)) {
418 $value = (float)$value;
420 // Just a normal string, right?
430 * Used in inlines to check for more inlines or quoted strings
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();
443 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
444 if (preg_match_all($regex,$inline,$strings)) {
445 $saved_strings = $strings[0];
446 $inline = preg_replace($regex,'YAMLString',$inline);
450 // Check for sequences
451 if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
452 $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
456 // Check for mappings
457 if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
458 $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
462 $explode = explode(', ',$inline);
465 // Re-add the sequences
468 foreach ($explode as $key => $value) {
469 if (strpos($value,'YAMLSeq') !== false) {
470 $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
476 // Re-add the mappings
479 foreach ($explode as $key => $value) {
480 if (strpos($value,'YAMLMap') !== false) {
481 $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
488 // Re-add the strings
489 if (!empty($saved_strings)) {
491 foreach ($explode as $key => $value) {
492 while (strpos($value,'YAMLString') !== false) {
493 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
495 $value = $explode[$key];
503 function literalBlockContinues ($line, $lineIndent) {
504 if (!trim($line)) return true;
505 if ($this->_getIndent($line) > $lineIndent) return true;
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;
520 function addArray ($array, $indent) {
521 if (count ($array) > 1)
522 return $this->addArrayInline ($array, $indent);
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
) {
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) . ';');
543 $this->_containsGroupAlias
= false;
547 // Adding string or numeric key to the innermost level or $this->arr.
549 $_arr[$key] = $value;
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) {
571 if (!empty ($array)) {
572 foreach ($array as $_) {
573 if (!is_int($_)) $_ = "'$_'";
574 $tempPath[] = "[$_]";
577 //end ($tempPath); $latestKey = key($tempPath);
578 $tempPath = implode ('', $tempPath);
584 function startsLiteralBlock ($line) {
585 $lastChar = substr (trim($line), -1);
586 if (in_array ($lastChar, $this->LiteralBlockMarkers
))
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";
602 $line = trim ($line, "\r\n ") . " ";
604 return $literalBlock . $line;
607 function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
609 foreach ($lineArray as $k => $_) {
611 $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
613 if (substr($_, -1 * strlen ($this->LiteralPlaceHolder
)) == $this->LiteralPlaceHolder
)
614 $lineArray[$k] = rtrim ($literalBlock, " \r\n");
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
;
631 end($linePath); $lastIndentInParentPath = key($linePath);
632 if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
633 } while ($indent <= $lastIndentInParentPath);
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]);
652 function isComment ($line) {
653 if (preg_match('/^#/', $line)) return true;
654 if (trim($line, " \r\n\t") == '---') return true;
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;
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, )
675 function isLiteral ($line) {
676 if ($this->isArrayElement($line)) return false;
677 if ($this->isHashElement($line)) return false;
682 function startsMappedSequence ($line) {
683 if (preg_match('/^-(.*):$/',$line)) return true;
686 function returnMappedSequence ($line) {
688 $key = trim(substr(substr($line,1),0,-1));
693 function returnMappedValue ($line) {
695 $key = trim(substr($line,0,-1));
700 function startsMappedValue ($line) {
701 if (preg_match('/^(.*):$/',$line)) return true;
704 function isPlainArray ($line) {
705 if (preg_match('/^\[(.*)\]$/', $line)) return true;
709 function returnPlainArray ($line) {
710 return $this->_toType($line);
713 function returnKeyValuePair ($line) {
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));
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);
736 $array[$key] = $value;
745 function returnArrayElement ($line) {
746 if (strlen($line) <= 1) return array(array()); // Weird %)
748 $value = trim(substr($line,1));
749 $value = $this->_toType($value);
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];
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));