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, 2006-2009 Vlad Andersen
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);
31 * Setting this to true will force YAMLDump to enclose any string value in
36 public $setting_dump_force_quotes = false;
52 private $_dumpWordWrap;
53 private $_containsGroupAnchor = false;
54 private $_containsGroupAlias = false;
57 private $LiteralBlockMarkers = array ('>', '|');
58 private $LiteralPlaceHolder = '___YAML_Literal_Block___';
59 private $SavedGroups = array();
62 * Path modifier that should be applied after adding current element.
65 private $delayedPath = array();
74 * Load YAML into a PHP array statically
76 * The load method, when supplied with a YAML stream (string or file),
77 * will do its best to convert YAML in a file into a PHP array. Pretty
81 * $array = Spyc::YAMLLoad('lucky.yaml');
86 * @param string $input Path of YAML file or string containing YAML
88 public static function YAMLLoad($input) {
90 return $Spyc->load($input);
94 * Load a string of YAML into a PHP array statically
96 * The load method, when supplied with a YAML string, will do its best
97 * to convert YAML in a string into a PHP array. Pretty simple.
99 * Note: use this function if you don't want files from the file system
100 * loaded and processed as YAML. This is of interest to people concerned
101 * about security whose input is from a string.
105 * $array = Spyc::YAMLLoadString("---\n0: hello world\n");
110 * @param string $input String containing YAML
112 public static function YAMLLoadString($input) {
114 return $Spyc->loadString($input);
118 * Dump YAML from PHP array statically
120 * The dump method, when supplied with an array, will do its best
121 * to convert the array into friendly YAML. Pretty simple. Feel free to
122 * save the returned string as nothing.yaml and pass it around.
124 * Oh, and you can decide how big the indent is and what the wordwrap
125 * for folding is. Pretty cool -- just pass in 'false' for either if
126 * you want to use the default.
128 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
129 * you can turn off wordwrap by passing in 0.
133 * @param array $array PHP array
134 * @param int $indent Pass in false to use the default, which is 2
135 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
137 public static function YAMLDump($array,$indent = false,$wordwrap = false) {
139 return $spyc->dump($array,$indent,$wordwrap);
144 * Dump PHP array to YAML
146 * The dump method, when supplied with an array, will do its best
147 * to convert the array into friendly YAML. Pretty simple. Feel free to
148 * save the returned string as tasteful.yaml and pass it around.
150 * Oh, and you can decide how big the indent is and what the wordwrap
151 * for folding is. Pretty cool -- just pass in 'false' for either if
152 * you want to use the default.
154 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
155 * you can turn off wordwrap by passing in 0.
159 * @param array $array PHP array
160 * @param int $indent Pass in false to use the default, which is 2
161 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
163 public function dump($array,$indent = false,$wordwrap = false) {
164 // Dumps to some very clean YAML. We'll have to add some more features
165 // and options soon. And better support for folding.
167 // New features and options.
168 if ($indent === false or !is_numeric($indent)) {
169 $this->_dumpIndent
= 2;
171 $this->_dumpIndent
= $indent;
174 if ($wordwrap === false or !is_numeric($wordwrap)) {
175 $this->_dumpWordWrap
= 40;
177 $this->_dumpWordWrap
= $wordwrap;
183 // Start at the base of the array and move through it.
184 foreach ($array as $key => $value) {
185 $string .= $this->_yamlize($key,$value,0);
191 * Attempts to convert a key / value array item to YAML
194 * @param $key The name of the key
195 * @param $value The value of the item
196 * @param $indent The indent of the current node
198 private function _yamlize($key,$value,$indent, $previous_key = -1) {
199 if (is_array($value)) {
200 // It has children. What to do?
201 // Make it the right kind of item
202 $string = $this->_dumpNode($key, NULL, $indent, $previous_key);
204 $indent +
= $this->_dumpIndent
;
206 $string .= $this->_yamlizeArray($value,$indent);
207 } elseif (!is_array($value)) {
208 // It doesn't have children. Yip.
209 $string = $this->_dumpNode($key, $value, $indent, $previous_key);
215 * Attempts to convert an array to YAML
218 * @param $array The array you want to convert
219 * @param $indent The indent of the current level
221 private function _yamlizeArray($array,$indent) {
222 if (is_array($array)) {
225 foreach ($array as $key => $value) {
226 $string .= $this->_yamlize($key, $value, $indent, $previous_key);
227 $previous_key = $key;
236 * Returns YAML from a key and a value
239 * @param $key The name of the key
240 * @param $value The value of the item
241 * @param $indent The indent of the current node
243 private function _dumpNode($key, $value, $indent, $previous_key = -1) {
244 // do some folding here, for blocks
245 if (strpos($value,"\n") !== false ||
strpos($value,": ") !== false ||
strpos($value,"- ") !== false ||
246 strpos($value,"#") !== false ||
strpos($value,"<") !== false ||
strpos($value,">") !== false) {
247 $value = $this->_doLiteralBlock($value,$indent);
249 $value = $this->_doFolding($value,$indent);
250 if (is_bool($value)) {
251 $value = ($value) ?
"true" : "false";
257 $spaces = str_repeat(' ',$indent);
259 if (is_int($key) && $key - 1 == $previous_key) {
261 $string = $spaces.'- '.$value."\n";
264 if (strpos($key, ":") !== false) { $key = '"' . $key . '"'; }
265 $string = $spaces.$key.': '.$value."\n";
271 * Creates a literal block for dumping
275 * @param $indent int The value of the indent
277 private function _doLiteralBlock($value,$indent) {
278 $exploded = explode("\n",$value);
280 $indent +
= $this->_dumpIndent
;
281 $spaces = str_repeat(' ',$indent);
282 foreach ($exploded as $line) {
283 $newValue .= "\n" . $spaces . trim($line);
289 * Folds a string of text, if necessary
292 * @param $value The string you wish to fold
294 private function _doFolding($value,$indent) {
295 // Don't do anything if wordwrap is set to 0
297 if ($this->_dumpWordWrap
!== 0 && strlen($value) > $this->_dumpWordWrap
) {
298 $indent +
= $this->_dumpIndent
;
299 $indent = str_repeat(' ',$indent);
300 $wrapped = wordwrap($value,$this->_dumpWordWrap
,"\n$indent");
301 $value = ">\n".$indent.$wrapped;
303 if ($this->setting_dump_force_quotes
&& is_string ($value))
304 $value = '"' . $value . '"';
313 private function load($input) {
314 $Source = $this->loadFromSource($input);
315 return $this->loadWithSource($Source);
318 private function loadString($input) {
319 $Source = $this->loadFromString($input);
320 return $this->loadWithSource($Source);
323 private function loadWithSource($Source) {
324 if (empty ($Source)) return array();
325 $this->path
= array();
326 $this->result
= array();
328 $cnt = count($Source);
329 for ($i = 0; $i < $cnt; $i++
) {
332 $this->indent
= strlen($line) - strlen(ltrim($line));
333 $tempPath = $this->getParentPathByIndent($this->indent
);
334 $line = self
::stripIndent($line, $this->indent
);
335 if (self
::isComment($line)) continue;
336 if (self
::isEmpty($line)) continue;
337 $this->path
= $tempPath;
339 $literalBlockStyle = $this->startsLiteralBlock($line);
340 if ($literalBlockStyle) {
341 $line = rtrim ($line, $literalBlockStyle . " \n");
343 $line .= $this->LiteralPlaceHolder
;
345 while (++
$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent
)) {
346 $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
351 while (++
$i < $cnt && self
::greedilyNeedNextLine($line)) {
352 $line = rtrim ($line, " \n\t\r") . ' ' . ltrim ($Source[$i], " \t");
358 $lineArray = $this->_parseLine($line);
360 if ($literalBlockStyle)
361 $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
363 $this->addArray($lineArray, $this->indent
);
365 foreach ($this->delayedPath
as $indent => $delayedPath)
366 $this->path
[$indent] = $delayedPath;
368 $this->delayedPath
= array();
371 return $this->result
;
374 private function loadFromSource ($input) {
375 if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
378 return $this->loadFromString($input);
381 private function loadFromString ($input) {
382 $lines = explode("\n",$input);
383 foreach ($lines as $k => $_) {
384 $lines[$k] = rtrim ($_, "\r");
390 * Parses YAML code and returns an array for a node
393 * @param string $line A line from the YAML file
395 private function _parseLine($line) {
396 if (!$line) return array();
398 if (!$line) return array();
401 $group = $this->nodeContainsGroup($line);
403 $this->addGroup($line, $group);
404 $line = $this->stripGroup ($line, $group);
407 if ($this->startsMappedSequence($line))
408 return $this->returnMappedSequence($line);
410 if ($this->startsMappedValue($line))
411 return $this->returnMappedValue($line);
413 if ($this->isArrayElement($line))
414 return $this->returnArrayElement($line);
416 if ($this->isPlainArray($line))
417 return $this->returnPlainArray($line);
420 return $this->returnKeyValuePair($line);
425 * Finds the type of the passed value, returns the value as the new type.
427 * @param string $value
430 private function _toType($value) {
431 if ($value === '') return null;
432 $first_character = $value[0];
433 $last_character = substr($value, -1, 1);
438 if ($first_character != '"' && $first_character != "'") break;
439 if ($last_character != '"' && $last_character != "'") break;
444 return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\'\'' => '\'', '\\\'' => '\''));
446 if (strpos($value, ' #') !== false)
447 $value = preg_replace('/\s+#(.+)$/','',$value);
449 if ($first_character == '[' && $last_character == ']') {
450 // Take out strings sequences and mappings
451 $explode = $this->_inlineEscape(trim(substr ($value, 1, -1)));
452 // Propagate value array
454 foreach ($explode as $v) {
455 $value[] = $this->_toType($v);
460 if (strpos($value,': ')!==false && $first_character != '{') {
462 $array = explode(': ',$value);
463 $key = trim($array[0]);
465 $value = trim(implode(': ',$array));
466 $value = $this->_toType($value);
467 return array($key => $value);
470 if ($first_character == '{' && $last_character == '}') {
472 // Take out strings sequences and mappings
473 $explode = $this->_inlineEscape(substr ($value, 1, -1));
474 // Propagate value array
476 foreach ($explode as $v) {
477 $SubArr = $this->_toType($v);
478 if (empty($SubArr)) continue;
479 if (is_array ($SubArr)) {
480 $array[key($SubArr)] = $SubArr[key($SubArr)]; continue;
487 if ($value == 'null' ||
$value == 'NULL' ||
$value == 'Null' ||
$value == '' ||
$value == '~') {
491 if (intval($first_character) > 0 && preg_match ('/^[1-9]+[0-9]*$/', $value)) {
492 $intvalue = (int)$value;
493 if ($intvalue != PHP_INT_MAX
)
499 array('true', 'on', '+', 'yes', 'y', 'True', 'TRUE', 'On', 'ON', 'YES', 'Yes', 'Y'))) {
503 if (in_array(strtolower($value),
504 array('false', 'off', '-', 'no', 'n'))) {
508 if (is_numeric($value)) {
509 if ($value === '0') return 0;
510 if (trim ($value, 0) === $value)
511 $value = (float)$value;
519 * Used in inlines to check for more inlines or quoted strings
523 private function _inlineEscape($inline) {
524 // There's gotta be a cleaner way to do this...
525 // While pure sequences seem to be nesting just fine,
526 // pure mappings and mappings with sequences inside can't go very
527 // deep. This needs to be fixed.
531 $saved_strings = array();
534 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
535 if (preg_match_all($regex,$inline,$strings)) {
536 $saved_strings = $strings[0];
537 $inline = preg_replace($regex,'YAMLString',$inline);
544 // Check for sequences
545 while (preg_match('/\[([^{}\[\]]+)\]/U',$inline,$matchseqs)) {
546 $seqs[] = $matchseqs[0];
547 $inline = preg_replace('/\[([^{}\[\]]+)\]/U', ('YAMLSeq' . (count($seqs) - 1) . 's'), $inline, 1);
550 // Check for mappings
551 while (preg_match('/{([^\[\]{}]+)}/U',$inline,$matchmaps)) {
552 $maps[] = $matchmaps[0];
553 $inline = preg_replace('/{([^\[\]{}]+)}/U', ('YAMLMap' . (count($maps) - 1) . 's'), $inline, 1);
556 if ($i++
>= 10) break;
558 } while (strpos ($inline, '[') !== false ||
strpos ($inline, '{') !== false);
560 $explode = explode(', ',$inline);
561 $stringi = 0; $i = 0;
565 // Re-add the sequences
567 foreach ($explode as $key => $value) {
568 if (strpos($value,'YAMLSeq') !== false) {
569 foreach ($seqs as $seqk => $seq) {
570 $explode[$key] = str_replace(('YAMLSeq'.$seqk.'s'),$seq,$value);
571 $value = $explode[$key];
577 // Re-add the mappings
579 foreach ($explode as $key => $value) {
580 if (strpos($value,'YAMLMap') !== false) {
581 foreach ($maps as $mapk => $map) {
582 $explode[$key] = str_replace(('YAMLMap'.$mapk.'s'), $map, $value);
583 $value = $explode[$key];
590 // Re-add the strings
591 if (!empty($saved_strings)) {
592 foreach ($explode as $key => $value) {
593 while (strpos($value,'YAMLString') !== false) {
594 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$stringi],$value, 1);
595 unset($saved_strings[$stringi]);
597 $value = $explode[$key];
603 foreach ($explode as $key => $value) {
604 if (strpos($value,'YAMLSeq') !== false) {
605 $finished = false; break;
607 if (strpos($value,'YAMLMap') !== false) {
608 $finished = false; break;
610 if (strpos($value,'YAMLString') !== false) {
611 $finished = false; break;
614 if ($finished) break;
618 break; // Prevent infinite loops.
624 private function literalBlockContinues ($line, $lineIndent) {
625 if (!trim($line)) return true;
626 if (strlen($line) - strlen(ltrim($line)) > $lineIndent) return true;
630 private function addArrayInline ($array, $indent) {
631 $CommonGroupPath = $this->path
;
632 if (empty ($array)) return false;
634 foreach ($array as $k => $_) {
635 $this->addArray(array($k => $_), $indent);
636 $this->path
= $CommonGroupPath;
641 private function addArray ($array, $indent) {
643 if (count ($array) > 1)
644 return $this->addArrayInline ($array, $indent);
648 if (!isset ($array[$key])) return false;
649 if ($array[$key] === array()) { $array[$key] = ''; };
650 $value = $array[$key];
652 $tempPath = Spyc
::flatten ($this->path
);
653 // Unfolding inner array tree.
654 $_arr = $this->result
;
655 foreach ($this->path
as $k) {
659 if ($this->_containsGroupAlias
) {
661 if (!isset($this->SavedGroups
[$this->_containsGroupAlias
])) { echo "Bad group name: $this->_containsGroupAlias."; break; }
662 $groupPath = $this->SavedGroups
[$this->_containsGroupAlias
];
663 $value = $this->result
;
664 foreach ($groupPath as $k) {
668 $this->_containsGroupAlias
= false;
672 // Adding string or numeric key to the innermost level or $this->arr.
674 $_arr[$key] = $value;
676 if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
677 else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
681 $this->path
[$indent] = $key;
684 eval ('$this->result' . $tempPath . ' = $_arr;');
686 if ($this->_containsGroupAnchor
) {
687 $this->SavedGroups
[$this->_containsGroupAnchor
] = $this->path
;
688 $this->_containsGroupAnchor
= false;
695 private static function flatten ($array) {
697 if (empty ($array)) return '';
698 foreach ($array as $_) {
699 if (!is_int($_)) $_ = '\'' . $_ . '\'';
700 $tempPath[] = '[' . $_ . ']';
702 return implode ('', $tempPath);
707 private function startsLiteralBlock ($line) {
708 $lastChar = substr (trim($line), -1);
709 if (in_array ($lastChar, $this->LiteralBlockMarkers
))
714 private static function greedilyNeedNextLine($line) {
715 $line = trim ($line);
716 if (!strlen($line)) return false;
717 if ($line[0] == '[' && substr ($line, -1, 1) != ']') return true;
721 private function addLiteralLine ($literalBlock, $line, $literalBlockStyle) {
722 $line = self
::stripIndent($line);
723 $line = rtrim ($line, "\r\n\t ") . "\n";
724 if ($line == "\n") $line = '';
726 if ($literalBlockStyle == '|') {
727 return $literalBlock . $line;
729 if (strlen($line) == 0)
730 return rtrim($literalBlock, ' ') . "\n";
733 $line = trim ($line, "\r\n ") . " ";
735 return $literalBlock . $line;
738 function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
739 foreach ($lineArray as $k => $_) {
741 $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
742 else if (substr($_, -1 * strlen ($this->LiteralPlaceHolder
)) == $this->LiteralPlaceHolder
)
743 $lineArray[$k] = rtrim ($literalBlock, " \r\n");
748 private static function stripIndent ($line, $indent = -1) {
749 if ($indent == -1) $indent = strlen($line) - strlen(ltrim($line));
750 return substr ($line, $indent);
753 private function getParentPathByIndent ($indent) {
754 if ($indent == 0) return array();
755 $linePath = $this->path
;
757 end($linePath); $lastIndentInParentPath = key($linePath);
758 if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
759 } while ($indent <= $lastIndentInParentPath);
764 private function clearBiggerPathValues ($indent) {
767 if ($indent == 0) $this->path
= array();
768 if (empty ($this->path
)) return true;
770 foreach ($this->path
as $k => $_) {
771 if ($k > $indent) unset ($this->path
[$k]);
778 private static function isComment ($line) {
779 if (!$line) return false;
780 if ($line[0] == '#') return true;
781 if (trim($line, " \r\n\t") == '---') return true;
785 private static function isEmpty ($line) {
786 return (trim ($line) === '');
790 private function isArrayElement ($line) {
791 if (!$line) return false;
792 if ($line[0] != '-') return false;
793 if (strlen ($line) > 3)
794 if (substr($line,0,3) == '---') return false;
799 private function isHashElement ($line) {
800 return strpos($line, ':');
803 private function isLiteral ($line) {
804 if ($this->isArrayElement($line)) return false;
805 if ($this->isHashElement($line)) return false;
810 private function startsMappedSequence ($line) {
811 return ($line[0] == '-' && substr ($line, -1, 1) == ':');
814 private function returnMappedSequence ($line) {
816 $key = trim(substr($line,1,-1));
817 $array[$key] = array();
818 $this->delayedPath
= array(strpos ($line, $key) +
$this->indent
=> $key);
819 return array($array);
822 private function returnMappedValue ($line) {
824 $key = trim(substr($line,0,-1));
829 private function startsMappedValue ($line) {
830 return (substr ($line, -1, 1) == ':');
833 private function isPlainArray ($line) {
834 return ($line[0] == '[' && substr ($line, -1, 1) == ']');
837 private function returnPlainArray ($line) {
838 return $this->_toType($line);
841 private function returnKeyValuePair ($line) {
843 if (strpos ($line, ':')) {
844 // It's a key/value pair most likely
845 // If the key is in double quotes pull it out
846 if (($line[0] == '"' ||
$line[0] == "'") && preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
847 $value = trim(str_replace($matches[1],'',$line));
850 // Do some guesswork as to the key and the value
851 $explode = explode(':',$line);
852 $key = trim($explode[0]);
853 array_shift($explode);
854 $value = trim(implode(':',$explode));
856 // Set the type of the value. Int, string, etc
857 $value = $this->_toType($value);
861 $array[$key] = $value;
870 private function returnArrayElement ($line) {
871 if (strlen($line) <= 1) return array(array()); // Weird %)
873 $value = trim(substr($line,1));
874 $value = $this->_toType($value);
880 private function nodeContainsGroup ($line) {
881 $symbolsForReference = 'A-z0-9_\-';
882 if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
883 if ($line[0] == '&' && preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
884 if ($line[0] == '*' && preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
885 if (preg_match('/(&['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
886 if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
891 private function addGroup ($line, $group) {
892 if ($group[0] == '&') $this->_containsGroupAnchor
= substr ($group, 1);
893 if ($group[0] == '*') $this->_containsGroupAlias
= substr ($group, 1);
894 //print_r ($this->path);
897 private function stripGroup ($line, $group) {
898 $line = trim(str_replace($group, '', $line));