3 * Spyc -- A Simple PHP YAML Class
5 * @author Vlad Andersen <vlad.andersen@gmail.com>
6 * @author Chris Wanstrath <chris@ozmm.org>
7 * @link https://github.com/mustangostang/spyc/
8 * @copyright Copyright 2005-2006 Chris Wanstrath, 2006-2011 Vlad Andersen
9 * @license http://www.opensource.org/licenses/mit-license.php MIT License
13 if (!function_exists('spyc_load')) {
15 * Parses YAML to array.
16 * @param string $string YAML string.
19 function spyc_load ($string) {
20 return Spyc::YAMLLoadString($string);
24 if (!function_exists('spyc_load_file')) {
26 * Parses YAML to array.
27 * @param string $file Path to YAML file.
30 function spyc_load_file ($file) {
31 return Spyc::YAMLLoad($file);
35 if (!function_exists('spyc_dump')) {
37 * Dumps array to YAML.
38 * @param array $data Array.
41 function spyc_dump ($data) {
42 return Spyc::YAMLDump($data, false, false, true);
46 if (!class_exists('Spyc')) {
49 * The Simple PHP YAML Class.
51 * This class can be used to read a YAML file and convert its contents
52 * into a PHP array. It currently supports a very limited subsection of
58 * $array = $Spyc->load($file);
62 * $array = Spyc::YAMLLoad($file);
66 * $array = spyc_load_file($file);
74 const REMPTY = "\0\0\0\0\0";
77 * Setting this to true will force YAMLDump to enclose any string value in
78 * quotes. False by default.
82 public $setting_dump_force_quotes = false;
85 * Setting this to true will forse YAMLLoad to use syck_load function when
86 * possible. False by default.
89 public $setting_use_syck_is_possible = false;
98 private $_dumpWordWrap;
99 private $_containsGroupAnchor = false;
100 private $_containsGroupAlias = false;
103 private $LiteralPlaceHolder = '___YAML_Literal_Block___';
104 private $SavedGroups = array();
107 * Path modifier that should be applied after adding current element.
110 private $delayedPath = array();
119 * Load a valid YAML string to Spyc.
120 * @param string $input
123 public function load ($input) {
124 return $this->_loadString($input);
128 * Load a valid YAML file to Spyc.
129 * @param string $file
132 public function loadFile ($file) {
133 return $this->_load($file);
137 * Load YAML into a PHP array statically
139 * The load method, when supplied with a YAML stream (string or file),
140 * will do its best to convert YAML in a file into a PHP array. Pretty
144 * $array = Spyc::YAMLLoad('lucky.yaml');
149 * @param string $input Path of YAML file or string containing YAML
151 public static function YAMLLoad($input) {
153 return $Spyc->_load($input);
157 * Load a string of YAML into a PHP array statically
159 * The load method, when supplied with a YAML string, will do its best
160 * to convert YAML in a string into a PHP array. Pretty simple.
162 * Note: use this function if you don't want files from the file system
163 * loaded and processed as YAML. This is of interest to people concerned
164 * about security whose input is from a string.
168 * $array = Spyc::YAMLLoadString("---\n0: hello world\n");
173 * @param string $input String containing YAML
175 public static function YAMLLoadString($input) {
177 return $Spyc->_loadString($input);
181 * Dump YAML from PHP array statically
183 * The dump method, when supplied with an array, will do its best
184 * to convert the array into friendly YAML. Pretty simple. Feel free to
185 * save the returned string as nothing.yaml and pass it around.
187 * Oh, and you can decide how big the indent is and what the wordwrap
188 * for folding is. Pretty cool -- just pass in 'false' for either if
189 * you want to use the default.
191 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
192 * you can turn off wordwrap by passing in 0.
196 * @param array|\stdClass $array PHP array
197 * @param int $indent Pass in false to use the default, which is 2
198 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
199 * @param bool $no_opening_dashes Do not start YAML file with "---\n"
201 public static function YAMLDump($array, $indent = false, $wordwrap = false, $no_opening_dashes = false) {
203 return $spyc->dump($array, $indent, $wordwrap, $no_opening_dashes);
208 * Dump PHP array to YAML
210 * The dump method, when supplied with an array, will do its best
211 * to convert the array into friendly YAML. Pretty simple. Feel free to
212 * save the returned string as tasteful.yaml and pass it around.
214 * Oh, and you can decide how big the indent is and what the wordwrap
215 * for folding is. Pretty cool -- just pass in 'false' for either if
216 * you want to use the default.
218 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
219 * you can turn off wordwrap by passing in 0.
223 * @param array $array PHP array
224 * @param int $indent Pass in false to use the default, which is 2
225 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
227 public function dump($array,$indent = false,$wordwrap = false, $no_opening_dashes = false) {
228 // Dumps to some very clean YAML. We'll have to add some more features
229 // and options soon. And better support for folding.
231 // New features and options.
232 if ($indent === false or !is_numeric($indent)) {
233 $this->_dumpIndent = 2;
235 $this->_dumpIndent = $indent;
238 if ($wordwrap === false or !is_numeric($wordwrap)) {
239 $this->_dumpWordWrap = 40;
241 $this->_dumpWordWrap = $wordwrap;
246 if (!$no_opening_dashes) $string = "---\n";
248 // Start at the base of the array and move through it.
250 $array = (array)$array;
252 foreach ($array as $key => $value) {
253 if (!isset($first_key)) $first_key = $key;
254 $string .= $this->_yamlize($key,$value,0,$previous_key, $first_key, $array);
255 $previous_key = $key;
262 * Attempts to convert a key / value array item to YAML
265 * @param $key The name of the key
266 * @param $value The value of the item
267 * @param $indent The indent of the current node
269 private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0, $source_array = null) {
270 if(is_object($value)) $value = (array)$value;
271 if (is_array($value)) {
273 return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array);
274 // It has children. What to do?
275 // Make it the right kind of item
276 $string = $this->_dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array);
278 $indent += $this->_dumpIndent;
280 $string .= $this->_yamlizeArray($value,$indent);
281 } elseif (!is_array($value)) {
282 // It doesn't have children. Yip.
283 $string = $this->_dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array);
289 * Attempts to convert an array to YAML
292 * @param $array The array you want to convert
293 * @param $indent The indent of the current level
295 private function _yamlizeArray($array,$indent) {
296 if (is_array($array)) {
299 foreach ($array as $key => $value) {
300 if (!isset($first_key)) $first_key = $key;
301 $string .= $this->_yamlize($key, $value, $indent, $previous_key, $first_key, $array);
302 $previous_key = $key;
311 * Returns YAML from a key and a value
314 * @param $key The name of the key
315 * @param $value The value of the item
316 * @param $indent The indent of the current node
318 private function _dumpNode($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null) {
319 // do some folding here, for blocks
320 if (is_string ($value) && ((strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false ||
321 strpos($value,"*") !== false || strpos($value,"#") !== false || strpos($value,"<") !== false || strpos($value,">") !== false || strpos ($value, '%') !== false || strpos ($value, ' ') !== false ||
322 strpos($value,"[") !== false || strpos($value,"]") !== false || strpos($value,"{") !== false || strpos($value,"}") !== false) || strpos($value,"&") !== false || strpos($value, "'") !== false || strpos($value, "!") === 0 ||
323 substr ($value, -1, 1) == ':')
325 $value = $this->_doLiteralBlock($value,$indent);
327 $value = $this->_doFolding($value,$indent);
330 if ($value === array()) $value = '[ ]';
331 if ($value === "") $value = '""';
332 if (self::isTranslationWord($value)) {
333 $value = $this->_doLiteralBlock($value, $indent);
335 if (trim ($value) != $value)
336 $value = $this->_doLiteralBlock($value,$indent);
338 if (is_bool($value)) {
339 $value = $value ? "true" : "false";
342 if ($value === null) $value = 'null';
343 if ($value === "'" . self::REMPTY . "'") $value = null;
345 $spaces = str_repeat(' ',$indent);
347 //if (is_int($key) && $key - 1 == $previous_key && $first_key===0) {
348 if (is_array ($source_array) && array_keys($source_array) === range(0, count($source_array) - 1)) {
350 $string = $spaces.'- '.$value."\n";
352 // if ($first_key===0) throw new Exception('Keys are all screwy. The first one was zero, now it\'s "'. $key .'"');
354 if (strpos($key, ":") !== false || strpos($key, "#") !== false) { $key = '"' . $key . '"'; }
355 $string = rtrim ($spaces.$key.': '.$value)."\n";
361 * Creates a literal block for dumping
365 * @param $indent int The value of the indent
367 private function _doLiteralBlock($value,$indent) {
368 if ($value === "\n") return '\n';
369 if (strpos($value, "\n") === false && strpos($value, "'") === false) {
370 return sprintf ("'%s'", $value);
372 if (strpos($value, "\n") === false && strpos($value, '"') === false) {
373 return sprintf ('"%s"', $value);
375 $exploded = explode("\n",$value);
377 if (isset($exploded[0]) && ($exploded[0] == "|" || $exploded[0] == "|-" || $exploded[0] == ">")) {
378 $newValue = $exploded[0];
381 $indent += $this->_dumpIndent;
382 $spaces = str_repeat(' ',$indent);
383 foreach ($exploded as $line) {
385 if (strpos($line, '"') === 0 && strrpos($line, '"') == (strlen($line)-1) || strpos($line, "'") === 0 && strrpos($line, "'") == (strlen($line)-1)) {
386 $line = substr($line, 1, -1);
388 $newValue .= "\n" . $spaces . ($line);
394 * Folds a string of text, if necessary
397 * @param $value The string you wish to fold
399 private function _doFolding($value,$indent) {
400 // Don't do anything if wordwrap is set to 0
402 if ($this->_dumpWordWrap !== 0 && is_string ($value) && strlen($value) > $this->_dumpWordWrap) {
403 $indent += $this->_dumpIndent;
404 $indent = str_repeat(' ',$indent);
405 $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
406 $value = ">\n".$indent.$wrapped;
408 if ($this->setting_dump_force_quotes && is_string ($value) && $value !== self::REMPTY)
409 $value = '"' . $value . '"';
410 if (is_numeric($value) && is_string($value))
411 $value = '"' . $value . '"';
418 private function isTrueWord($value) {
419 $words = self::getTranslations(array('true', 'on', 'yes', 'y'));
420 return in_array($value, $words, true);
423 private function isFalseWord($value) {
424 $words = self::getTranslations(array('false', 'off', 'no', 'n'));
425 return in_array($value, $words, true);
428 private function isNullWord($value) {
429 $words = self::getTranslations(array('null', '~'));
430 return in_array($value, $words, true);
433 private function isTranslationWord($value) {
435 self::isTrueWord($value) ||
436 self::isFalseWord($value) ||
437 self::isNullWord($value)
442 * Coerce a string into a native type
443 * Reference: http://yaml.org/type/bool.html
444 * TODO: Use only words from the YAML spec.
446 * @param $value The value to coerce
448 private function coerceValue(&$value) {
449 if (self::isTrueWord($value)) {
451 } else if (self::isFalseWord($value)) {
453 } else if (self::isNullWord($value)) {
459 * Given a set of words, perform the appropriate translations on them to
460 * match the YAML 1.1 specification for type coercing.
461 * @param $words The words to translate
464 private static function getTranslations(array $words) {
466 foreach ($words as $i) {
467 $result = array_merge($result, array(ucfirst($i), strtoupper($i), strtolower($i)));
474 private function _load($input) {
475 $Source = $this->loadFromSource($input);
476 return $this->loadWithSource($Source);
479 private function _loadString($input) {
480 $Source = $this->loadFromString($input);
481 return $this->loadWithSource($Source);
484 private function loadWithSource($Source) {
485 if (empty ($Source)) return array();
486 if ($this->setting_use_syck_is_possible && function_exists ('syck_load')) {
487 $array = syck_load (implode ("\n", $Source));
488 return is_array($array) ? $array : array();
491 $this->path = array();
492 $this->result = array();
494 $cnt = count($Source);
495 for ($i = 0; $i < $cnt; $i++) {
498 $this->indent = strlen($line) - strlen(ltrim($line));
499 $tempPath = $this->getParentPathByIndent($this->indent);
500 $line = self::stripIndent($line, $this->indent);
501 if (self::isComment($line)) continue;
502 if (self::isEmpty($line)) continue;
503 $this->path = $tempPath;
505 $literalBlockStyle = self::startsLiteralBlock($line);
506 if ($literalBlockStyle) {
507 $line = rtrim ($line, $literalBlockStyle . " \n");
509 $line .= ' '.$this->LiteralPlaceHolder;
510 $literal_block_indent = strlen($Source[$i+1]) - strlen(ltrim($Source[$i+1]));
511 while (++$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent)) {
512 $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle, $literal_block_indent);
517 // Strip out comments
518 if (strpos ($line, '#')) {
519 $line = preg_replace('/\s*#([^"\']+)$/','',$line);
522 while (++$i < $cnt && self::greedilyNeedNextLine($line)) {
523 $line = rtrim ($line, " \n\t\r") . ' ' . ltrim ($Source[$i], " \t");
527 $lineArray = $this->_parseLine($line);
529 if ($literalBlockStyle)
530 $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
532 $this->addArray($lineArray, $this->indent);
534 foreach ($this->delayedPath as $indent => $delayedPath)
535 $this->path[$indent] = $delayedPath;
537 $this->delayedPath = array();
540 return $this->result;
543 private function loadFromSource ($input) {
544 if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
545 $input = file_get_contents($input);
547 return $this->loadFromString($input);
550 private function loadFromString ($input) {
551 $lines = explode("\n",$input);
552 foreach ($lines as $k => $_) {
553 $lines[$k] = rtrim ($_, "\r");
559 * Parses YAML code and returns an array for a node
562 * @param string $line A line from the YAML file
564 private function _parseLine($line) {
565 if (!$line) return array();
567 if (!$line) return array();
571 $group = $this->nodeContainsGroup($line);
573 $this->addGroup($line, $group);
574 $line = $this->stripGroup ($line, $group);
577 if ($this->startsMappedSequence($line))
578 return $this->returnMappedSequence($line);
580 if ($this->startsMappedValue($line))
581 return $this->returnMappedValue($line);
583 if ($this->isArrayElement($line))
584 return $this->returnArrayElement($line);
586 if ($this->isPlainArray($line))
587 return $this->returnPlainArray($line);
590 return $this->returnKeyValuePair($line);
595 * Finds the type of the passed value, returns the value as the new type.
597 * @param string $value
600 private function _toType($value) {
601 if ($value === '') return "";
602 $first_character = $value[0];
603 $last_character = substr($value, -1, 1);
608 if ($first_character != '"' && $first_character != "'") break;
609 if ($last_character != '"' && $last_character != "'") break;
614 $value = str_replace('\n', "\n", $value);
615 if ($first_character == "'")
616 return strtr(substr ($value, 1, -1), array ('\'\'' => '\'', '\\\''=> '\''));
617 return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\\\''=> '\''));
620 if (strpos($value, ' #') !== false && !$is_quoted)
621 $value = preg_replace('/\s+#(.+)$/','',$value);
623 if ($first_character == '[' && $last_character == ']') {
624 // Take out strings sequences and mappings
625 $innerValue = trim(substr ($value, 1, -1));
626 if ($innerValue === '') return array();
627 $explode = $this->_inlineEscape($innerValue);
628 // Propagate value array
630 foreach ($explode as $v) {
631 $value[] = $this->_toType($v);
636 if (strpos($value,': ')!==false && $first_character != '{') {
637 $array = explode(': ',$value);
638 $key = trim($array[0]);
640 $value = trim(implode(': ',$array));
641 $value = $this->_toType($value);
642 return array($key => $value);
645 if ($first_character == '{' && $last_character == '}') {
646 $innerValue = trim(substr ($value, 1, -1));
647 if ($innerValue === '') return array();
649 // Take out strings sequences and mappings
650 $explode = $this->_inlineEscape($innerValue);
651 // Propagate value array
653 foreach ($explode as $v) {
654 $SubArr = $this->_toType($v);
655 if (empty($SubArr)) continue;
656 if (is_array ($SubArr)) {
657 $array[key($SubArr)] = $SubArr[key($SubArr)]; continue;
664 if ($value == 'null' || $value == 'NULL' || $value == 'Null' || $value == '' || $value == '~') {
668 if ( is_numeric($value) && preg_match ('/^(-|)[1-9]+[0-9]*$/', $value) ){
669 $intvalue = (int)$value;
670 if ($intvalue != PHP_INT_MAX && $intvalue != ~PHP_INT_MAX)
675 if ( is_string($value) && preg_match('/^0[xX][0-9a-fA-F]+$/', $value)) {
676 // Hexadecimal value.
677 return hexdec($value);
680 $this->coerceValue($value);
682 if (is_numeric($value)) {
683 if ($value === '0') return 0;
684 if (rtrim ($value, 0) === $value)
685 $value = (float)$value;
693 * Used in inlines to check for more inlines or quoted strings
697 private function _inlineEscape($inline) {
698 // There's gotta be a cleaner way to do this...
699 // While pure sequences seem to be nesting just fine,
700 // pure mappings and mappings with sequences inside can't go very
701 // deep. This needs to be fixed.
705 $saved_strings = array();
706 $saved_empties = array();
708 // Check for empty strings
709 $regex = '/("")|(\'\')/';
710 if (preg_match_all($regex,$inline,$strings)) {
711 $saved_empties = $strings[0];
712 $inline = preg_replace($regex,'YAMLEmpty',$inline);
717 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
718 if (preg_match_all($regex,$inline,$strings)) {
719 $saved_strings = $strings[0];
720 $inline = preg_replace($regex,'YAMLString',$inline);
729 // Check for sequences
730 while (preg_match('/\[([^{}\[\]]+)\]/U',$inline,$matchseqs)) {
731 $seqs[] = $matchseqs[0];
732 $inline = preg_replace('/\[([^{}\[\]]+)\]/U', ('YAMLSeq' . (count($seqs) - 1) . 's'), $inline, 1);
735 // Check for mappings
736 while (preg_match('/{([^\[\]{}]+)}/U',$inline,$matchmaps)) {
737 $maps[] = $matchmaps[0];
738 $inline = preg_replace('/{([^\[\]{}]+)}/U', ('YAMLMap' . (count($maps) - 1) . 's'), $inline, 1);
741 if ($i++ >= 10) break;
743 } while (strpos ($inline, '[') !== false || strpos ($inline, '{') !== false);
745 $explode = explode(',',$inline);
746 $explode = array_map('trim', $explode);
747 $stringi = 0; $i = 0;
751 // Re-add the sequences
753 foreach ($explode as $key => $value) {
754 if (strpos($value,'YAMLSeq') !== false) {
755 foreach ($seqs as $seqk => $seq) {
756 $explode[$key] = str_replace(('YAMLSeq'.$seqk.'s'),$seq,$value);
757 $value = $explode[$key];
763 // Re-add the mappings
765 foreach ($explode as $key => $value) {
766 if (strpos($value,'YAMLMap') !== false) {
767 foreach ($maps as $mapk => $map) {
768 $explode[$key] = str_replace(('YAMLMap'.$mapk.'s'), $map, $value);
769 $value = $explode[$key];
776 // Re-add the strings
777 if (!empty($saved_strings)) {
778 foreach ($explode as $key => $value) {
779 while (strpos($value,'YAMLString') !== false) {
780 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$stringi],$value, 1);
781 unset($saved_strings[$stringi]);
783 $value = $explode[$key];
789 // Re-add the empties
790 if (!empty($saved_empties)) {
791 foreach ($explode as $key => $value) {
792 while (strpos($value,'YAMLEmpty') !== false) {
793 $explode[$key] = preg_replace('/YAMLEmpty/', '', $value, 1);
794 $value = $explode[$key];
800 foreach ($explode as $key => $value) {
801 if (strpos($value,'YAMLSeq') !== false) {
802 $finished = false; break;
804 if (strpos($value,'YAMLMap') !== false) {
805 $finished = false; break;
807 if (strpos($value,'YAMLString') !== false) {
808 $finished = false; break;
810 if (strpos($value,'YAMLEmpty') !== false) {
811 $finished = false; break;
814 if ($finished) break;
818 break; // Prevent infinite loops.
825 private function literalBlockContinues ($line, $lineIndent) {
826 if (!trim($line)) return true;
827 if (strlen($line) - strlen(ltrim($line)) > $lineIndent) return true;
831 private function referenceContentsByAlias ($alias) {
833 if (!isset($this->SavedGroups[$alias])) { echo "Bad group name: $alias."; break; }
834 $groupPath = $this->SavedGroups[$alias];
835 $value = $this->result;
836 foreach ($groupPath as $k) {
843 private function addArrayInline ($array, $indent) {
844 $CommonGroupPath = $this->path;
845 if (empty ($array)) return false;
847 foreach ($array as $k => $_) {
848 $this->addArray(array($k => $_), $indent);
849 $this->path = $CommonGroupPath;
854 private function addArray ($incoming_data, $incoming_indent) {
856 // print_r ($incoming_data);
858 if (count ($incoming_data) > 1)
859 return $this->addArrayInline ($incoming_data, $incoming_indent);
861 $key = key ($incoming_data);
862 $value = isset($incoming_data[$key]) ? $incoming_data[$key] : null;
863 if ($key === '__!YAMLZero') $key = '0';
865 if ($incoming_indent == 0 && !$this->_containsGroupAlias && !$this->_containsGroupAnchor) { // Shortcut for root-level values.
866 if ($key || $key === '' || $key === '0') {
867 $this->result[$key] = $value;
869 $this->result[] = $value; end ($this->result); $key = key ($this->result);
871 $this->path[$incoming_indent] = $key;
878 // Unfolding inner array tree.
879 $history[] = $_arr = $this->result;
880 foreach ($this->path as $k) {
881 $history[] = $_arr = $_arr[$k];
884 if ($this->_containsGroupAlias) {
885 $value = $this->referenceContentsByAlias($this->_containsGroupAlias);
886 $this->_containsGroupAlias = false;
890 // Adding string or numeric key to the innermost level or $this->arr.
891 if (is_string($key) && $key == '<<') {
892 if (!is_array ($_arr)) { $_arr = array (); }
894 $_arr = array_merge ($_arr, $value);
895 } else if ($key || $key === '' || $key === '0') {
896 if (!is_array ($_arr))
897 $_arr = array ($key=>$value);
899 $_arr[$key] = $value;
901 if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
902 else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
905 $reverse_path = array_reverse($this->path);
906 $reverse_history = array_reverse ($history);
907 $reverse_history[0] = $_arr;
908 $cnt = count($reverse_history) - 1;
909 for ($i = 0; $i < $cnt; $i++) {
910 $reverse_history[$i+1][$reverse_path[$i]] = $reverse_history[$i];
912 $this->result = $reverse_history[$cnt];
914 $this->path[$incoming_indent] = $key;
916 if ($this->_containsGroupAnchor) {
917 $this->SavedGroups[$this->_containsGroupAnchor] = $this->path;
918 if (is_array ($value)) {
921 $this->SavedGroups[$this->_containsGroupAnchor][$incoming_indent + 2] = $k;
924 $this->_containsGroupAnchor = false;
929 private static function startsLiteralBlock ($line) {
930 $lastChar = substr (trim($line), -1);
931 if ($lastChar != '>' && $lastChar != '|') return false;
932 if ($lastChar == '|') return $lastChar;
933 // HTML tags should not be counted as literal blocks.
934 if (preg_match ('#<.*?>$#', $line)) return false;
938 private static function greedilyNeedNextLine($line) {
939 $line = trim ($line);
940 if (!strlen($line)) return false;
941 if (substr ($line, -1, 1) == ']') return false;
942 if ($line[0] == '[') return true;
943 if (preg_match ('#^[^:]+?:\s*\[#', $line)) return true;
947 private function addLiteralLine ($literalBlock, $line, $literalBlockStyle, $indent = -1) {
948 $line = self::stripIndent($line, $indent);
949 if ($literalBlockStyle !== '|') {
950 $line = self::stripIndent($line);
952 $line = rtrim ($line, "\r\n\t ") . "\n";
953 if ($literalBlockStyle == '|') {
954 return $literalBlock . $line;
956 if (strlen($line) == 0)
957 return rtrim($literalBlock, ' ') . "\n";
958 if ($line == "\n" && $literalBlockStyle == '>') {
959 return rtrim ($literalBlock, " \t") . "\n";
962 $line = trim ($line, "\r\n ") . " ";
963 return $literalBlock . $line;
966 function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
967 foreach ($lineArray as $k => $_) {
969 $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
970 else if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder)
971 $lineArray[$k] = rtrim ($literalBlock, " \r\n");
976 private static function stripIndent ($line, $indent = -1) {
977 if ($indent == -1) $indent = strlen($line) - strlen(ltrim($line));
978 return substr ($line, $indent);
981 private function getParentPathByIndent ($indent) {
982 if ($indent == 0) return array();
983 $linePath = $this->path;
985 end($linePath); $lastIndentInParentPath = key($linePath);
986 if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
987 } while ($indent <= $lastIndentInParentPath);
992 private function clearBiggerPathValues ($indent) {
995 if ($indent == 0) $this->path = array();
996 if (empty ($this->path)) return true;
998 foreach ($this->path as $k => $_) {
999 if ($k > $indent) unset ($this->path[$k]);
1006 private static function isComment ($line) {
1007 if (!$line) return false;
1008 if ($line[0] == '#') return true;
1009 if (trim($line, " \r\n\t") == '---') return true;
1013 private static function isEmpty ($line) {
1014 return (trim ($line) === '');
1018 private function isArrayElement ($line) {
1019 if (!$line || !is_scalar($line)) return false;
1020 if (substr($line, 0, 2) != '- ') return false;
1021 if (strlen ($line) > 3)
1022 if (substr($line,0,3) == '---') return false;
1027 private function isHashElement ($line) {
1028 return strpos($line, ':');
1031 private function isLiteral ($line) {
1032 if ($this->isArrayElement($line)) return false;
1033 if ($this->isHashElement($line)) return false;
1038 private static function unquote ($value) {
1039 if (!$value) return $value;
1040 if (!is_string($value)) return $value;
1041 if ($value[0] == '\'') return trim ($value, '\'');
1042 if ($value[0] == '"') return trim ($value, '"');
1046 private function startsMappedSequence ($line) {
1047 return (substr($line, 0, 2) == '- ' && substr ($line, -1, 1) == ':');
1050 private function returnMappedSequence ($line) {
1052 $key = self::unquote(trim(substr($line,1,-1)));
1053 $array[$key] = array();
1054 $this->delayedPath = array(strpos ($line, $key) + $this->indent => $key);
1055 return array($array);
1058 private function checkKeysInValue($value) {
1059 if (strchr('[{"\'', $value[0]) === false) {
1060 if (strchr($value, ': ') !== false) {
1061 throw new Exception('Too many keys: '.$value);
1066 private function returnMappedValue ($line) {
1067 $this->checkKeysInValue($line);
1069 $key = self::unquote (trim(substr($line,0,-1)));
1074 private function startsMappedValue ($line) {
1075 return (substr ($line, -1, 1) == ':');
1078 private function isPlainArray ($line) {
1079 return ($line[0] == '[' && substr ($line, -1, 1) == ']');
1082 private function returnPlainArray ($line) {
1083 return $this->_toType($line);
1086 private function returnKeyValuePair ($line) {
1089 if (strpos ($line, ': ')) {
1090 // It's a key/value pair most likely
1091 // If the key is in double quotes pull it out
1092 if (($line[0] == '"' || $line[0] == "'") && preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
1093 $value = trim(str_replace($matches[1],'',$line));
1096 // Do some guesswork as to the key and the value
1097 $explode = explode(': ', $line);
1098 $key = trim(array_shift($explode));
1099 $value = trim(implode(': ', $explode));
1100 $this->checkKeysInValue($value);
1102 // Set the type of the value. Int, string, etc
1103 $value = $this->_toType($value);
1104 if ($key === '0') $key = '__!YAMLZero';
1105 $array[$key] = $value;
1107 $array = array ($line);
1114 private function returnArrayElement ($line) {
1115 if (strlen($line) <= 1) return array(array()); // Weird %)
1117 $value = trim(substr($line,1));
1118 $value = $this->_toType($value);
1119 if ($this->isArrayElement($value)) {
1120 $value = $this->returnArrayElement($value);
1127 private function nodeContainsGroup ($line) {
1128 $symbolsForReference = 'A-z0-9_\-';
1129 if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
1130 if ($line[0] == '&' && preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
1131 if ($line[0] == '*' && preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
1132 if (preg_match('/(&['.$symbolsForReference.']+)$/', $line, $matches)) return $matches[1];
1133 if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
1134 if (preg_match ('#^\s*<<\s*:\s*(\*[^\s]+).*$#', $line, $matches)) return $matches[1];
1139 private function addGroup ($line, $group) {
1140 if ($group[0] == '&') $this->_containsGroupAnchor = substr ($group, 1);
1141 if ($group[0] == '*') $this->_containsGroupAlias = substr ($group, 1);
1142 //print_r ($this->path);
1145 private function stripGroup ($line, $group) {
1146 $line = trim(str_replace($group, '', $line));
1152 // Enable use of Spyc from command line
1153 // The syntax is the following: php Spyc.php spyc.yaml
1156 if (PHP_SAPI != 'cli') break;
1157 if (empty ($_SERVER['argc']) || $_SERVER['argc'] < 2) break;
1158 if (empty ($_SERVER['PHP_SELF']) || FALSE === strpos ($_SERVER['PHP_SELF'], 'Spyc.php') ) break;
1160 echo json_encode (spyc_load_file ($file));