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);
40 private $_dumpWordWrap;
41 private $_containsGroupAnchor = false;
42 private $_containsGroupAlias = false;
45 private $LiteralBlockMarkers = array ('>', '|');
46 private $LiteralPlaceHolder = '___YAML_Literal_Block___';
47 private $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 public static function YAMLLoad($input) {
72 return $Spyc->load($input);
76 * Load a string of YAML into a PHP array statically
78 * The load method, when supplied with a YAML string, will do its best
79 * to convert YAML in a string into a PHP array. Pretty simple.
81 * Note: use this function if you don't want files from the file system
82 * loaded and processed as YAML. This is of interest to people concerned
83 * about security whose input is from a string.
87 * $array = Spyc::YAMLLoadString("---\n0: hello world\n");
92 * @param string $input String containing YAML
94 public static function YAMLLoadString($input) {
96 return $Spyc->loadString($input);
100 * Dump YAML from PHP array statically
102 * The dump method, when supplied with an array, will do its best
103 * to convert the array into friendly YAML. Pretty simple. Feel free to
104 * save the returned string as nothing.yaml and pass it around.
106 * Oh, and you can decide how big the indent is and what the wordwrap
107 * for folding is. Pretty cool -- just pass in 'false' for either if
108 * you want to use the default.
110 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
111 * you can turn off wordwrap by passing in 0.
115 * @param array $array PHP array
116 * @param int $indent Pass in false to use the default, which is 2
117 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
119 public static function YAMLDump($array,$indent = false,$wordwrap = false) {
121 return $spyc->dump($array,$indent,$wordwrap);
126 * Dump PHP array to YAML
128 * The dump method, when supplied with an array, will do its best
129 * to convert the array into friendly YAML. Pretty simple. Feel free to
130 * save the returned string as tasteful.yaml and pass it around.
132 * Oh, and you can decide how big the indent is and what the wordwrap
133 * for folding is. Pretty cool -- just pass in 'false' for either if
134 * you want to use the default.
136 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
137 * you can turn off wordwrap by passing in 0.
141 * @param array $array PHP array
142 * @param int $indent Pass in false to use the default, which is 2
143 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
145 public function dump($array,$indent = false,$wordwrap = false) {
146 // Dumps to some very clean YAML. We'll have to add some more features
147 // and options soon. And better support for folding.
149 // New features and options.
150 if ($indent === false or !is_numeric($indent)) {
151 $this->_dumpIndent
= 2;
153 $this->_dumpIndent
= $indent;
156 if ($wordwrap === false or !is_numeric($wordwrap)) {
157 $this->_dumpWordWrap
= 40;
159 $this->_dumpWordWrap
= $wordwrap;
165 // Start at the base of the array and move through it.
166 foreach ($array as $key => $value) {
167 $string .= $this->_yamlize($key,$value,0);
173 * Attempts to convert a key / value array item to YAML
176 * @param $key The name of the key
177 * @param $value The value of the item
178 * @param $indent The indent of the current node
180 private function _yamlize($key,$value,$indent) {
181 if (is_array($value)) {
182 // It has children. What to do?
183 // Make it the right kind of item
184 $string = $this->_dumpNode($key,NULL,$indent);
186 $indent +
= $this->_dumpIndent
;
188 $string .= $this->_yamlizeArray($value,$indent);
189 } elseif (!is_array($value)) {
190 // It doesn't have children. Yip.
191 $string = $this->_dumpNode($key,$value,$indent);
197 * Attempts to convert an array to YAML
200 * @param $array The array you want to convert
201 * @param $indent The indent of the current level
203 private function _yamlizeArray($array,$indent) {
204 if (is_array($array)) {
206 foreach ($array as $key => $value) {
207 $string .= $this->_yamlize($key,$value,$indent);
216 * Returns YAML from a key and a value
219 * @param $key The name of the key
220 * @param $value The value of the item
221 * @param $indent The indent of the current node
223 private function _dumpNode($key,$value,$indent) {
224 // do some folding here, for blocks
225 if (strpos($value,"\n") !== false ||
strpos($value,": ") !== false ||
strpos($value,"- ") !== false) {
226 $value = $this->_doLiteralBlock($value,$indent);
228 $value = $this->_doFolding($value,$indent);
231 if (is_bool($value)) {
232 $value = ($value) ?
"true" : "false";
235 $spaces = str_repeat(' ',$indent);
239 $string = $spaces.'- '.$value."\n";
242 if (strpos($key, ":") !== false) { $key = '"' . $key . '"'; }
243 $string = $spaces.$key.': '.$value."\n";
249 * Creates a literal block for dumping
253 * @param $indent int The value of the indent
255 private function _doLiteralBlock($value,$indent) {
256 $exploded = explode("\n",$value);
258 $indent +
= $this->_dumpIndent
;
259 $spaces = str_repeat(' ',$indent);
260 foreach ($exploded as $line) {
261 $newValue .= "\n" . $spaces . trim($line);
267 * Folds a string of text, if necessary
270 * @param $value The string you wish to fold
272 private function _doFolding($value,$indent) {
273 // Don't do anything if wordwrap is set to 0
274 if ($this->_dumpWordWrap
=== 0) {
278 if (strlen($value) > $this->_dumpWordWrap
) {
279 $indent +
= $this->_dumpIndent
;
280 $indent = str_repeat(' ',$indent);
281 $wrapped = wordwrap($value,$this->_dumpWordWrap
,"\n$indent");
282 $value = ">\n".$indent.$wrapped;
287 /* LOADING FUNCTIONS */
289 private function load($input) {
290 $Source = $this->loadFromSource($input);
291 return $this->loadWithSource($Source);
294 private function loadString($input) {
295 $Source = $this->loadFromString($input);
296 return $this->loadWithSource($Source);
299 private function loadWithSource($Source) {
300 if (empty ($Source)) return array();
301 $this->path
= array();
302 $this->result
= array();
305 for ($i = 0; $i < count($Source); $i++
) {
308 $lineIndent = $this->_getIndent($line);
309 $this->path
= $this->getParentPathByIndent($lineIndent);
310 $line = $this->stripIndent($line, $lineIndent);
311 if ($this->isComment($line)) continue;
313 if ($literalBlockStyle = $this->startsLiteralBlock($line)) {
314 $line = rtrim ($line, $literalBlockStyle . "\n");
316 $line .= $this->LiteralPlaceHolder
;
318 while (++
$i < count($Source) && $this->literalBlockContinues($Source[$i], $lineIndent)) {
319 $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
323 $lineArray = $this->_parseLine($line);
324 if ($literalBlockStyle)
325 $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
327 $this->addArray($lineArray, $lineIndent);
329 return $this->result
;
332 private function loadFromSource ($input) {
333 if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
336 return $this->loadFromString($input);
339 function loadFromString ($input) {
340 $lines = explode("\n",$input);
341 foreach ($lines as $k => $_) {
342 $lines[$k] = trim ($_, "\r");
348 * Finds and returns the indentation of a YAML line
351 * @param string $line A line from the YAML file
353 private function _getIndent($line) {
354 if (!preg_match('/^ +/',$line,$match)) return 0;
355 if (!empty($match[0])) return strlen ($match[0]);
360 * Parses YAML code and returns an array for a node
363 * @param string $line A line from the YAML file
365 private function _parseLine($line) {
366 if (!$line) return array();
368 if (!$line) return array();
371 if ($group = $this->nodeContainsGroup($line)) {
372 $this->addGroup($line, $group);
373 $line = $this->stripGroup ($line, $group);
376 if ($this->startsMappedSequence($line))
377 return $this->returnMappedSequence($line);
379 if ($this->startsMappedValue($line))
380 return $this->returnMappedValue($line);
382 if ($this->isArrayElement($line))
383 return $this->returnArrayElement($line);
385 if ($this->isPlainArray($line))
386 return $this->returnPlainArray($line);
389 return $this->returnKeyValuePair($line);
394 * Finds the type of the passed value, returns the value as the new type.
396 * @param string $value
399 private function _toType($value) {
403 if (substr($value, 0, 1) != '"' && substr($value, 0, 1) != "'") break;
404 if (substr($value, -1, 1) != '"' && substr($value, -1, 1) != "'") break;
408 if (!$is_quoted && strpos($value, ' #') !== false)
409 $value = preg_replace('/\s+#(.+)$/','',$value);
411 if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
412 $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
413 $value = preg_replace('/\\\\"/','"',$value);
414 } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
417 // Take out strings sequences and mappings
418 $explode = $this->_inlineEscape($matches[1]);
420 // Propagate value array
422 foreach ($explode as $v) {
423 $value[] = $this->_toType($v);
425 } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
427 $array = explode(': ',$value);
428 $key = trim($array[0]);
430 $value = trim(implode(': ',$array));
431 $value = $this->_toType($value);
432 $value = array($key => $value);
433 } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
436 // Take out strings sequences and mappings
437 $explode = $this->_inlineEscape($matches[1]);
439 // Propogate value array
441 foreach ($explode as $v) {
442 $SubArr = $this->_toType($v);
443 if (empty($SubArr)) continue;
444 if (is_array ($SubArr)) {
445 $array[key($SubArr)] = $SubArr[key($SubArr)]; continue;
450 } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
452 } elseif (preg_match ('/^[1-9]+[0-9]*$/', $value)) {
453 $intvalue = (int)$value;
454 if ($intvalue != PHP_INT_MAX
)
456 } elseif (in_array(strtolower($value),
457 array('true', 'on', '+', 'yes', 'y'))) {
459 } elseif (in_array(strtolower($value),
460 array('false', 'off', '-', 'no', 'n'))) {
462 } elseif (is_numeric($value)) {
463 if ($value === '0') return 0;
464 if (trim ($value, 0) === $value)
465 $value = (float)$value;
467 // Just a normal string, right?
477 * Used in inlines to check for more inlines or quoted strings
481 private function _inlineEscape($inline) {
482 // There's gotta be a cleaner way to do this...
483 // While pure sequences seem to be nesting just fine,
484 // pure mappings and mappings with sequences inside can't go very
485 // deep. This needs to be fixed.
487 $saved_strings = array();
490 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
491 if (preg_match_all($regex,$inline,$strings)) {
492 $saved_strings = $strings[0];
493 $inline = preg_replace($regex,'YAMLString',$inline);
497 // Check for sequences
498 if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
499 $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
503 // Check for mappings
504 if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
505 $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
509 $explode = explode(', ',$inline);
512 // Re-add the sequences
515 foreach ($explode as $key => $value) {
516 if (strpos($value,'YAMLSeq') !== false) {
517 $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
523 // Re-add the mappings
526 foreach ($explode as $key => $value) {
527 if (strpos($value,'YAMLMap') !== false) {
528 $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
535 // Re-add the strings
536 if (!empty($saved_strings)) {
538 foreach ($explode as $key => $value) {
539 while (strpos($value,'YAMLString') !== false) {
540 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
542 $value = $explode[$key];
550 private function literalBlockContinues ($line, $lineIndent) {
551 if (!trim($line)) return true;
552 if ($this->_getIndent($line) > $lineIndent) return true;
556 private function addArrayInline ($array, $indent) {
557 $CommonGroupPath = $this->path
;
558 if (empty ($array)) return false;
560 foreach ($array as $k => $_) {
561 $this->addArray(array($k => $_), $indent);
562 $this->path
= $CommonGroupPath;
567 private function addArray ($array, $indent) {
569 if (count ($array) > 1)
570 return $this->addArrayInline ($array, $indent);
574 if (!isset ($array[$key])) return false;
575 if ($array[$key] === array()) { $array[$key] = ''; };
576 $value = $array[$key];
578 // Unfolding inner array tree as defined in $this->_arrpath.
579 //$_arr = $this->result; $_tree[0] = $_arr; $i = 1;
581 $tempPath = Spyc
::flatten ($this->path
);
582 eval ('$_arr = $this->result' . $tempPath . ';');
585 if ($this->_containsGroupAlias
) {
587 if (!isset($this->SavedGroups
[$this->_containsGroupAlias
])) { echo "Bad group name: $this->_containsGroupAlias."; break; }
588 $groupPath = $this->SavedGroups
[$this->_containsGroupAlias
];
589 eval ('$value = $this->result' . Spyc
::flatten ($groupPath) . ';');
591 $this->_containsGroupAlias
= false;
595 // Adding string or numeric key to the innermost level or $this->arr.
597 $_arr[$key] = $value;
599 if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
600 else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
604 $this->path
[$indent] = $key;
606 eval ('$this->result' . $tempPath . ' = $_arr;');
608 if ($this->_containsGroupAnchor
) {
609 $this->SavedGroups
[$this->_containsGroupAnchor
] = $this->path
;
610 $this->_containsGroupAnchor
= false;
617 private function flatten ($array) {
619 if (!empty ($array)) {
620 foreach ($array as $_) {
621 if (!is_int($_)) $_ = "'$_'";
622 $tempPath[] = "[$_]";
625 //end ($tempPath); $latestKey = key($tempPath);
626 $tempPath = implode ('', $tempPath);
632 private function startsLiteralBlock ($line) {
633 $lastChar = substr (trim($line), -1);
634 if (in_array ($lastChar, $this->LiteralBlockMarkers
))
639 private function addLiteralLine ($literalBlock, $line, $literalBlockStyle) {
640 $line = $this->stripIndent($line);
641 $line = str_replace ("\r\n", "\n", $line);
643 if ($literalBlockStyle == '|') {
644 return $literalBlock . $line;
646 if (strlen($line) == 0) return $literalBlock . "\n";
650 $line = trim ($line, "\r\n ") . " ";
652 return $literalBlock . $line;
655 function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
656 foreach ($lineArray as $k => $_) {
658 $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
659 else if (substr($_, -1 * strlen ($this->LiteralPlaceHolder
)) == $this->LiteralPlaceHolder
)
660 $lineArray[$k] = rtrim ($literalBlock, " \r\n");
665 private function stripIndent ($line, $indent = -1) {
666 if ($indent == -1) $indent = $this->_getIndent($line);
667 return substr ($line, $indent);
670 private function getParentPathByIndent ($indent) {
672 if ($indent == 0) return array();
674 $linePath = $this->path
;
676 end($linePath); $lastIndentInParentPath = key($linePath);
677 if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
678 } while ($indent <= $lastIndentInParentPath);
683 private function clearBiggerPathValues ($indent) {
686 if ($indent == 0) $this->path
= array();
687 if (empty ($this->path
)) return true;
689 foreach ($this->path
as $k => $_) {
690 if ($k > $indent) unset ($this->path
[$k]);
697 private function isComment ($line) {
698 if (preg_match('/^#/', $line)) return true;
699 if (trim($line, " \r\n\t") == '---') return true;
703 private function isArrayElement ($line) {
704 if (!$line) return false;
705 if ($line[0] != '-') return false;
706 if (strlen ($line) > 3)
707 if (substr($line,0,3) == '---') return false;
712 private function isHashElement ($line) {
713 if (!preg_match('/^(.+?):/', $line, $matches)) return false;
714 $allegedKey = $matches[1];
715 if ($allegedKey) return true;
716 //if (substr_count($allegedKey, )
720 private function isLiteral ($line) {
721 if ($this->isArrayElement($line)) return false;
722 if ($this->isHashElement($line)) return false;
727 private function startsMappedSequence ($line) {
728 if (preg_match('/^-(.*):$/',$line)) return true;
731 private function returnMappedSequence ($line) {
733 $key = trim(substr(substr($line,1),0,-1));
738 private function returnMappedValue ($line) {
740 $key = trim(substr($line,0,-1));
745 private function startsMappedValue ($line) {
746 if (preg_match('/^(.*):$/',$line)) return true;
749 private function isPlainArray ($line) {
750 if (preg_match('/^\[(.*)\]$/', $line)) return true;
754 private function returnPlainArray ($line) {
755 return $this->_toType($line);
758 private function returnKeyValuePair ($line) {
762 if (preg_match('/^(.+):/',$line,$key)) {
763 // It's a key/value pair most likely
764 // If the key is in double quotes pull it out
765 if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
766 $value = trim(str_replace($matches[1],'',$line));
769 // Do some guesswork as to the key and the value
770 $explode = explode(':',$line);
771 $key = trim($explode[0]);
772 array_shift($explode);
773 $value = trim(implode(':',$explode));
776 // Set the type of the value. Int, string, etc
777 $value = $this->_toType($value);
781 $array[$key] = $value;
790 private function returnArrayElement ($line) {
791 if (strlen($line) <= 1) return array(array()); // Weird %)
793 $value = trim(substr($line,1));
794 $value = $this->_toType($value);
800 private function nodeContainsGroup ($line) {
801 $symbolsForReference = 'A-z0-9_\-';
802 if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
803 if (preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
804 if (preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
805 if (preg_match('/(&['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
806 if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
811 private function addGroup ($line, $group) {
812 if (substr ($group, 0, 1) == '&') $this->_containsGroupAnchor
= substr ($group, 1);
813 if (substr ($group, 0, 1) == '*') $this->_containsGroupAlias
= substr ($group, 1);
814 //print_r ($this->path);
817 private function stripGroup ($line, $group) {
818 $line = trim(str_replace($group, '', $line));