3 * Spyc -- A Simple PHP YAML Class
4 * @version 0.2.(5) -- 2006-12-31
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
14 * A node, used by Spyc for parsing YAML.
39 var $children = false;
42 * The constructor assigns the node a unique ID.
46 function YAMLNode($nodeId) {
52 * The Simple PHP YAML Class.
54 * This class can be used to read a YAML file and convert its contents
55 * into a PHP array. It currently supports a very limited subsection of
61 * $array = $parser->load($file);
68 * Load YAML into a PHP array statically
70 * The load method, when supplied with a YAML stream (string or file),
71 * will do its best to convert YAML in a file into a PHP array. Pretty
75 * $array = Spyc::YAMLLoad('lucky.yaml');
80 * @param string $input Path of YAML file or string containing YAML
82 function YAMLLoad($input) {
84 return $spyc->load($input);
88 * Dump YAML from PHP array statically
90 * The dump method, when supplied with an array, will do its best
91 * to convert the array into friendly YAML. Pretty simple. Feel free to
92 * save the returned string as nothing.yaml and pass it around.
94 * Oh, and you can decide how big the indent is and what the wordwrap
95 * for folding is. Pretty cool -- just pass in 'false' for either if
96 * you want to use the default.
98 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
99 * you can turn off wordwrap by passing in 0.
103 * @param array $array PHP array
104 * @param int $indent Pass in false to use the default, which is 2
105 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
107 function YAMLDump($array,$indent = false,$wordwrap = false) {
109 return $spyc->dump($array,$indent,$wordwrap);
113 * Load YAML into a PHP array from an instantiated object
115 * The load method, when supplied with a YAML stream (string or file path),
116 * will do its best to convert the YAML into a PHP array. Pretty simple.
119 * $parser = new Spyc;
120 * $array = $parser->load('lucky.yaml');
125 * @param string $input Path of YAML file or string containing YAML
127 function load($input) {
128 // See what type of input we're talking about
129 // If it's not a file, assume it's a string
130 if (!empty($input) && (strpos($input, "\n") === false)
131 && file_exists($input)) {
132 $yaml = file($input);
134 $yaml = explode("\n",$input);
136 // Initiate some objects and values
137 $base = new YAMLNode (1);
139 $this->_lastIndent
= 0;
140 $this->_lastNode
= $base->id
;
141 $this->_inBlock
= false;
142 $this->_isInline
= false;
145 foreach ($yaml as $linenum => $line) {
146 $ifchk = trim($line);
148 // If the line starts with a tab (instead of a space), throw a fit.
149 if (preg_match('/^(\t)+(\w+)/', $line)) {
150 $err = 'ERROR: Line '. ($linenum +
1) .' in your input YAML begins'.
151 ' with a tab. YAML only recognizes spaces. Please reformat.';
155 if ($this->_inBlock
=== false && empty($ifchk)) {
157 } elseif ($this->_inBlock
== true && empty($ifchk)) {
158 $last =& $this->_allNodes
[$this->_lastNode
];
159 $last->data
[key($last->data
)] .= "\n";
160 } elseif ($ifchk{0} != '#' && substr($ifchk,0,3) != '---') {
161 // Create a new node and get its indent
162 $node = new YAMLNode ($this->_nodeId
);
165 $node->indent
= $this->_getIndent($line);
167 // Check where the node lies in the hierarchy
168 if ($this->_lastIndent
== $node->indent
) {
169 // If we're in a block, add the text to the parent's data
170 if ($this->_inBlock
=== true) {
171 $parent =& $this->_allNodes
[$this->_lastNode
];
172 $parent->data
[key($parent->data
)] .= trim($line).$this->_blockEnd
;
174 // The current node's parent is the same as the previous node's
175 if (isset($this->_allNodes
[$this->_lastNode
])) {
176 $node->parent
= $this->_allNodes
[$this->_lastNode
]->parent
;
179 } elseif ($this->_lastIndent
< $node->indent
) {
180 if ($this->_inBlock
=== true) {
181 $parent =& $this->_allNodes
[$this->_lastNode
];
182 $parent->data
[key($parent->data
)] .= trim($line).$this->_blockEnd
;
183 } elseif ($this->_inBlock
=== false) {
184 // The current node's parent is the previous node
185 $node->parent
= $this->_lastNode
;
187 // If the value of the last node's data was > or | we need to
188 // start blocking i.e. taking in all lines as a text value until
189 // we drop our indent.
190 $parent =& $this->_allNodes
[$node->parent
];
191 $this->_allNodes
[$node->parent
]->children
= true;
192 if (is_array($parent->data
)) {
194 if (isset ($parent->data
[key($parent->data
)]))
195 $chk = $parent->data
[key($parent->data
)];
197 $this->_inBlock
= true;
198 $this->_blockEnd
= ' ';
199 $parent->data
[key($parent->data
)] =
200 str_replace('>','',$parent->data
[key($parent->data
)]);
201 $parent->data
[key($parent->data
)] .= trim($line).' ';
202 $this->_allNodes
[$node->parent
]->children
= false;
203 $this->_lastIndent
= $node->indent
;
204 } elseif ($chk === '|') {
205 $this->_inBlock
= true;
206 $this->_blockEnd
= "\n";
207 $parent->data
[key($parent->data
)] =
208 str_replace('|','',$parent->data
[key($parent->data
)]);
209 $parent->data
[key($parent->data
)] .= trim($line)."\n";
210 $this->_allNodes
[$node->parent
]->children
= false;
211 $this->_lastIndent
= $node->indent
;
215 } elseif ($this->_lastIndent
> $node->indent
) {
216 // Any block we had going is dead now
217 if ($this->_inBlock
=== true) {
218 $this->_inBlock
= false;
219 if ($this->_blockEnd
= "\n") {
220 $last =& $this->_allNodes
[$this->_lastNode
];
221 $last->data
[key($last->data
)] =
222 trim($last->data
[key($last->data
)]);
226 // We don't know the parent of the node so we have to find it
227 // foreach ($this->_allNodes as $n) {
228 foreach ($this->_indentSort
[$node->indent
] as $n) {
229 if ($n->indent
== $node->indent
) {
230 $node->parent
= $n->parent
;
235 if ($this->_inBlock
=== false) {
236 // Set these properties with information from our current node
237 $this->_lastIndent
= $node->indent
;
239 $this->_lastNode
= $node->id
;
240 // Parse the YAML line and return its data
241 $node->data
= $this->_parseLine($line);
242 // Add the node to the master list
243 $this->_allNodes
[$node->id
] = $node;
244 // Add a reference to the parent list
245 $this->_allParent
[intval($node->parent
)][] = $node->id
;
246 // Add a reference to the node in an indent array
247 $this->_indentSort
[$node->indent
][] =& $this->_allNodes
[$node->id
];
248 // Add a reference to the node in a References array if this node
249 // has a YAML reference in it.
251 ( (is_array($node->data
)) &&
252 isset($node->data
[key($node->data
)]) &&
253 (!is_array($node->data
[key($node->data
)])) )
255 ( (preg_match('/^&([^ ]+)/',$node->data
[key($node->data
)]))
257 (preg_match('/^\*([^ ]+)/',$node->data
[key($node->data
)])) )
259 $this->_haveRefs
[] =& $this->_allNodes
[$node->id
];
261 ( (is_array($node->data
)) &&
262 isset($node->data
[key($node->data
)]) &&
263 (is_array($node->data
[key($node->data
)])) )
265 // Incomplete reference making code. Ugly, needs cleaned up.
266 foreach ($node->data
[key($node->data
)] as $d) {
267 if ( !is_array($d) &&
268 ( (preg_match('/^&([^ ]+)/',$d))
270 (preg_match('/^\*([^ ]+)/',$d)) )
272 $this->_haveRefs
[] =& $this->_allNodes
[$node->id
];
281 // Here we travel through node-space and pick out references (& and *)
282 $this->_linkReferences();
284 // Build the PHP array out of node-space
285 $trunk = $this->_buildArray();
290 * Dump PHP array to YAML
292 * The dump method, when supplied with an array, will do its best
293 * to convert the array into friendly YAML. Pretty simple. Feel free to
294 * save the returned string as tasteful.yaml and pass it around.
296 * Oh, and you can decide how big the indent is and what the wordwrap
297 * for folding is. Pretty cool -- just pass in 'false' for either if
298 * you want to use the default.
300 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
301 * you can turn off wordwrap by passing in 0.
305 * @param array $array PHP array
306 * @param int $indent Pass in false to use the default, which is 2
307 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
309 function dump($array,$indent = false,$wordwrap = false) {
310 // Dumps to some very clean YAML. We'll have to add some more features
311 // and options soon. And better support for folding.
313 // New features and options.
314 if ($indent === false or !is_numeric($indent)) {
315 $this->_dumpIndent
= 2;
317 $this->_dumpIndent
= $indent;
320 if ($wordwrap === false or !is_numeric($wordwrap)) {
321 $this->_dumpWordWrap
= 40;
323 $this->_dumpWordWrap
= $wordwrap;
329 // Start at the base of the array and move through it.
330 foreach ($array as $key => $value) {
331 $string .= $this->_yamlize($key,$value,0);
336 /**** Private Properties ****/
353 /**** Public Properties ****/
362 /**** Private Methods ****/
365 * Attempts to convert a key / value array item to YAML
368 * @param $key The name of the key
369 * @param $value The value of the item
370 * @param $indent The indent of the current node
372 function _yamlize($key,$value,$indent) {
373 if (is_array($value)) {
374 // It has children. What to do?
375 // Make it the right kind of item
376 $string = $this->_dumpNode($key,NULL,$indent);
378 $indent +
= $this->_dumpIndent
;
380 $string .= $this->_yamlizeArray($value,$indent);
381 } elseif (!is_array($value)) {
382 // It doesn't have children. Yip.
383 $string = $this->_dumpNode($key,$value,$indent);
389 * Attempts to convert an array to YAML
392 * @param $array The array you want to convert
393 * @param $indent The indent of the current level
395 function _yamlizeArray($array,$indent) {
396 if (is_array($array)) {
398 foreach ($array as $key => $value) {
399 $string .= $this->_yamlize($key,$value,$indent);
408 * Returns YAML from a key and a value
411 * @param $key The name of the key
412 * @param $value The value of the item
413 * @param $indent The indent of the current node
415 function _dumpNode($key,$value,$indent) {
416 // do some folding here, for blocks
417 if (strpos($value,"\n") !== false ||
strpos($value,": ") !== false ||
strpos($value,"- ") !== false) {
418 $value = $this->_doLiteralBlock($value,$indent);
420 $value = $this->_doFolding($value,$indent);
423 if (is_bool($value)) {
424 $value = ($value) ?
"true" : "false";
427 $spaces = str_repeat(' ',$indent);
431 $string = $spaces.'- '.$value."\n";
434 $string = $spaces.$key.': '.$value."\n";
440 * Creates a literal block for dumping
444 * @param $indent int The value of the indent
446 function _doLiteralBlock($value,$indent) {
447 $exploded = explode("\n",$value);
449 $indent +
= $this->_dumpIndent
;
450 $spaces = str_repeat(' ',$indent);
451 foreach ($exploded as $line) {
452 $newValue .= "\n" . $spaces . trim($line);
458 * Folds a string of text, if necessary
461 * @param $value The string you wish to fold
463 function _doFolding($value,$indent) {
464 // Don't do anything if wordwrap is set to 0
465 if ($this->_dumpWordWrap
=== 0) {
469 if (strlen($value) > $this->_dumpWordWrap
) {
470 $indent +
= $this->_dumpIndent
;
471 $indent = str_repeat(' ',$indent);
472 $wrapped = wordwrap($value,$this->_dumpWordWrap
,"\n$indent");
473 $value = ">\n".$indent.$wrapped;
478 /* Methods used in loading */
481 * Finds and returns the indentation of a YAML line
484 * @param string $line A line from the YAML file
486 function _getIndent($line) {
487 preg_match('/^\s{1,}/',$line,$match);
488 if (!empty($match[0])) {
489 $indent = substr_count($match[0],' ');
497 * Parses YAML code and returns an array for a node
500 * @param string $line A line from the YAML file
502 function _parseLine($line) {
507 if (preg_match('/^-(.*):$/',$line)) {
508 // It's a mapped sequence
509 $key = trim(substr(substr($line,1),0,-1));
511 } elseif ($line[0] == '-' && substr($line,0,3) != '---') {
512 // It's a list item but not a new stream
513 if (strlen($line) > 1) {
514 $value = trim(substr($line,1));
515 // Set the type of the value. Int, string, etc
516 $value = $this->_toType($value);
521 } elseif (preg_match('/^(.+):/',$line,$key)) {
522 // It's a key/value pair most likely
523 // If the key is in double quotes pull it out
524 if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
525 $value = trim(str_replace($matches[1],'',$line));
528 // Do some guesswork as to the key and the value
529 $explode = explode(':',$line);
530 $key = trim($explode[0]);
531 array_shift($explode);
532 $value = trim(implode(':',$explode));
535 // Set the type of the value. Int, string, etc
536 $value = $this->_toType($value);
540 $array[$key] = $value;
547 * Finds the type of the passed value, returns the value as the new type.
549 * @param string $value
552 function _toType($value) {
553 if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
554 $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
555 $value = preg_replace('/\\\\"/','"',$value);
556 } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
559 // Take out strings sequences and mappings
560 $explode = $this->_inlineEscape($matches[1]);
562 // Propogate value array
564 foreach ($explode as $v) {
565 $value[] = $this->_toType($v);
567 } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
569 $array = explode(': ',$value);
570 $key = trim($array[0]);
572 $value = trim(implode(': ',$array));
573 $value = $this->_toType($value);
574 $value = array($key => $value);
575 } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
578 // Take out strings sequences and mappings
579 $explode = $this->_inlineEscape($matches[1]);
581 // Propogate value array
583 foreach ($explode as $v) {
584 $array = $array +
$this->_toType($v);
587 } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
589 } elseif (preg_match ('/^[0-9]+$/', $value)) {
590 // Cheeky change for compartibility with PHP < 4.2.0
591 $value = (int)$value;
592 } elseif (in_array(strtolower($value),
593 array('true', 'on', '+', 'yes', 'y'))) {
595 } elseif (in_array(strtolower($value),
596 array('false', 'off', '-', 'no', 'n'))) {
598 } elseif (is_numeric($value)) {
599 $value = (float)$value;
601 // Just a normal string, right?
602 $value = trim(preg_replace('/#(.+)$/','',$value));
609 * Used in inlines to check for more inlines or quoted strings
613 function _inlineEscape($inline) {
614 // There's gotta be a cleaner way to do this...
615 // While pure sequences seem to be nesting just fine,
616 // pure mappings and mappings with sequences inside can't go very
617 // deep. This needs to be fixed.
619 $saved_strings = array();
622 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
623 if (preg_match_all($regex,$inline,$strings)) {
624 $saved_strings = $strings[0];
625 $inline = preg_replace($regex,'YAMLString',$inline);
629 // Check for sequences
630 if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
631 $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
635 // Check for mappings
636 if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
637 $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
641 $explode = explode(', ',$inline);
644 // Re-add the sequences
647 foreach ($explode as $key => $value) {
648 if (strpos($value,'YAMLSeq') !== false) {
649 $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
655 // Re-add the mappings
658 foreach ($explode as $key => $value) {
659 if (strpos($value,'YAMLMap') !== false) {
660 $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
666 // Re-add the strings
667 if (!empty($saved_strings)) {
669 foreach ($explode as $key => $value) {
670 while (strpos($value,'YAMLString') !== false) {
671 $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
673 $value = $explode[$key];
682 * Builds the PHP array from all the YAML nodes we've gathered
686 function _buildArray() {
689 if (!isset($this->_indentSort
[0])) {
693 foreach ($this->_indentSort
[0] as $n) {
694 if (empty($n->parent
)) {
695 $this->_nodeArrayizeData($n);
696 // Check for references and copy the needed data to complete them.
697 $this->_makeReferences($n);
698 // Merge our data with the big array we're building
699 $trunk = $this->_array_kmerge($trunk,$n->data
);
707 * Traverses node-space and sets references (& and *) accordingly
711 function _linkReferences() {
712 if (is_array($this->_haveRefs
)) {
713 foreach ($this->_haveRefs
as $node) {
714 if (!empty($node->data
)) {
715 $key = key($node->data
);
716 // If it's an array, don't check.
717 if (is_array($node->data
[$key])) {
718 foreach ($node->data
[$key] as $k => $v) {
719 $this->_linkRef($node,$key,$k,$v);
722 $this->_linkRef($node,$key);
730 function _linkRef(&$n,$key,$k = NULL,$v = NULL) {
731 if (empty($k) && empty($v)) {
733 if (preg_match('/^&([^ ]+)/',$n->data
[$key],$matches)) {
734 // Flag the node so we know it's a reference
735 $this->_allNodes
[$n->id
]->ref
= substr($matches[0],1);
736 $this->_allNodes
[$n->id
]->data
[$key] =
737 substr($n->data
[$key],strlen($matches[0])+
1);
739 } elseif (preg_match('/^\*([^ ]+)/',$n->data
[$key],$matches)) {
740 $ref = substr($matches[0],1);
741 // Flag the node as having a reference
742 $this->_allNodes
[$n->id
]->refKey
= $ref;
744 } elseif (!empty($k) && !empty($v)) {
745 if (preg_match('/^&([^ ]+)/',$v,$matches)) {
746 // Flag the node so we know it's a reference
747 $this->_allNodes
[$n->id
]->ref
= substr($matches[0],1);
748 $this->_allNodes
[$n->id
]->data
[$key][$k] =
749 substr($v,strlen($matches[0])+
1);
751 } elseif (preg_match('/^\*([^ ]+)/',$v,$matches)) {
752 $ref = substr($matches[0],1);
753 // Flag the node as having a reference
754 $this->_allNodes
[$n->id
]->refKey
= $ref;
760 * Finds the children of a node and aids in the building of the PHP array
762 * @param int $nid The id of the node whose children we're gathering
765 function _gatherChildren($nid) {
767 $node =& $this->_allNodes
[$nid];
768 if (is_array ($this->_allParent
[$node->id
])) {
769 foreach ($this->_allParent
[$node->id
] as $nodeZ) {
770 $z =& $this->_allNodes
[$nodeZ];
772 $this->_nodeArrayizeData($z);
773 // Check for references
774 $this->_makeReferences($z);
775 // Merge with the big array we're returning
776 // The big array being all the data of the children of our parent node
777 $return = $this->_array_kmerge($return,$z->data
);
784 * Turns a node's data and its children's data into a PHP array
787 * @param array $node The node which you want to arrayize
790 function _nodeArrayizeData(&$node) {
791 if (is_array($node->data
) && $node->children
== true) {
792 // This node has children, so we need to find them
793 $childs = $this->_gatherChildren($node->id
);
794 // We've gathered all our children's data and are ready to use it
795 $key = key($node->data
);
796 $key = empty($key) ?
0 : $key;
797 // If it's an array, add to it of course
798 if (isset ($node->data
[$key])) {
799 if (is_array($node->data
[$key])) {
800 $node->data
[$key] = $this->_array_kmerge($node->data
[$key],$childs);
802 $node->data
[$key] = $childs;
805 $node->data
[$key] = $childs;
807 } elseif (!is_array($node->data
) && $node->children
== true) {
808 // Same as above, find the children of this node
809 $childs = $this->_gatherChildren($node->id
);
810 $node->data
= array();
811 $node->data
[] = $childs;
814 // We edited $node by reference, so just return true
819 * Traverses node-space and copies references to / from this object.
821 * @param object $z A node whose references we wish to make real
824 function _makeReferences(&$z) {
826 if (isset($z->ref
)) {
827 $key = key($z->data
);
828 // Copy the data to this object for easy retrieval later
829 $this->ref
[$z->ref
] =& $z->data
[$key];
830 // It has a reference
831 } elseif (isset($z->refKey
)) {
832 if (isset($this->ref
[$z->refKey
])) {
833 $key = key($z->data
);
834 // Copy the data from this object to make the node a real reference
835 $z->data
[$key] =& $this->ref
[$z->refKey
];
843 * Merges arrays and maintains numeric keys.
845 * An ever-so-slightly modified version of the array_kmerge() function posted
846 * to php.net by mail at nospam dot iaindooley dot com on 2004-04-08.
848 * http://us3.php.net/manual/en/function.array-merge.php#41394
855 function _array_kmerge($arr1,$arr2) {
856 if(!is_array($arr1)) $arr1 = array();
857 if(!is_array($arr2)) $arr2 = array();
859 $keys = array_merge(array_keys($arr1),array_keys($arr2));
860 $vals = array_merge(array_values($arr1),array_values($arr2));
862 foreach($keys as $key) {
863 list($unused,$val) = each($vals);
864 if (isset($ret[$key]) and is_int($key)) $ret[] = $val; else $ret[$key] = $val;