3 * Spyc -- A Simple PHP YAML Class
4 * @version 0.2.3 -- 2006-02-04
5 * @author Chris Wanstrath <chris@ozmm.org>
6 * @see http://spyc.sourceforge.net/
7 * @copyright Copyright 2005-2006 Chris Wanstrath
8 * @license http://www.opensource.org/licenses/mit-license.php MIT License
12 * A node, used by Spyc for parsing YAML.
37 var $children = false;
40 * The constructor assigns the node a unique ID.
45 $this->id
= uniqid('');
50 * The Simple PHP YAML Class.
52 * This class can be used to read a YAML file and convert its contents
53 * into a PHP array. It currently supports a very limited subsection of
59 * $array = $parser->load($file);
66 * Load YAML into a PHP array statically
68 * The load method, when supplied with a YAML stream (string or file),
69 * will do its best to convert YAML in a file into a PHP array. Pretty
73 * $array = Spyc::YAMLLoad('lucky.yml');
78 * @param string $input Path of YAML file or string containing YAML
80 function YAMLLoad($input) {
82 return $spyc->load($input);
86 * Dump YAML from PHP array statically
88 * The dump method, when supplied with an array, will do its best
89 * to convert the array into friendly YAML. Pretty simple. Feel free to
90 * save the returned string as nothing.yml and pass it around.
92 * Oh, and you can decide how big the indent is and what the wordwrap
93 * for folding is. Pretty cool -- just pass in 'false' for either if
94 * you want to use the default.
96 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
97 * you can turn off wordwrap by passing in 0.
102 * @param array $array PHP array
103 * @param int $indent Pass in false to use the default, which is 2
104 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
106 public static function YAMLDump($array,$indent = false,$wordwrap = false) {
108 return $spyc->dump($array,$indent,$wordwrap);
112 * Load YAML into a PHP array from an instantiated object
114 * The load method, when supplied with a YAML stream (string or file path),
115 * will do its best to convert the YAML into a PHP array. Pretty simple.
118 * $parser = new Spyc;
119 * $array = $parser->load('lucky.yml');
124 * @param string $input Path of YAML file or string containing YAML
126 function load($input) {
127 // See what type of input we're talking about
128 // If it's not a file, assume it's a string
129 if (!empty($input) && (strpos($input, "\n") === false)
130 && file_exists($input)) {
131 $yaml = file($input);
133 $yaml = explode("\n",$input);
135 // Initiate some objects and values
136 $base = new YAMLNode
;
138 $this->_lastIndent
= 0;
139 $this->_lastNode
= $base->id
;
140 $this->_inBlock
= false;
141 $this->_isInline
= false;
143 foreach ($yaml as $linenum => $line) {
144 $ifchk = trim($line);
146 // If the line starts with a tab (instead of a space), throw a fit.
147 if (preg_match('/^(\t)+(\w+)/', $line)) {
148 $err = 'ERROR: Line '. ($linenum +
1) .' in your input YAML begins'.
149 ' with a tab. YAML only recognizes spaces. Please reformat.';
153 if ($this->_inBlock
=== false && empty($ifchk)) {
155 } elseif ($this->_inBlock
== true && empty($ifchk)) {
156 $last =& $this->_allNodes
[$this->_lastNode
];
157 $last->data
[key($last->data
)] .= "\n";
158 } elseif ($ifchk{0} != '#' && substr($ifchk,0,3) != '---') {
159 // Create a new node and get its indent
160 $node = new YAMLNode
;
161 $node->indent
= $this->_getIndent($line);
163 // Check where the node lies in the hierarchy
164 if ($this->_lastIndent
== $node->indent
) {
165 // If we're in a block, add the text to the parent's data
166 if ($this->_inBlock
=== true) {
167 $parent =& $this->_allNodes
[$this->_lastNode
];
168 $parent->data
[key($parent->data
)] .= trim($line).$this->_blockEnd
;
170 // The current node's parent is the same as the previous node's
171 if (isset($this->_allNodes
[$this->_lastNode
])) {
172 $node->parent
= $this->_allNodes
[$this->_lastNode
]->parent
;
175 } elseif ($this->_lastIndent
< $node->indent
) {
176 if ($this->_inBlock
=== true) {
177 $parent =& $this->_allNodes
[$this->_lastNode
];
178 $parent->data
[key($parent->data
)] .= trim($line).$this->_blockEnd
;
179 } elseif ($this->_inBlock
=== false) {
180 // The current node's parent is the previous node
181 $node->parent
= $this->_lastNode
;
183 // If the value of the last node's data was > or | we need to
184 // start blocking i.e. taking in all lines as a text value until
185 // we drop our indent.
186 $parent =& $this->_allNodes
[$node->parent
];
187 $this->_allNodes
[$node->parent
]->children
= true;
188 if (is_array($parent->data
)) {
189 $chk = $parent->data
[key($parent->data
)];
191 $this->_inBlock
= true;
192 $this->_blockEnd
= ' ';
193 $parent->data
[key($parent->data
)] =
194 str_replace('>','',$parent->data
[key($parent->data
)]);
195 $parent->data
[key($parent->data
)] .= trim($line).' ';
196 $this->_allNodes
[$node->parent
]->children
= false;
197 $this->_lastIndent
= $node->indent
;
198 } elseif ($chk === '|') {
199 $this->_inBlock
= true;
200 $this->_blockEnd
= "\n";
201 $parent->data
[key($parent->data
)] =
202 str_replace('|','',$parent->data
[key($parent->data
)]);
203 $parent->data
[key($parent->data
)] .= trim($line)."\n";
204 $this->_allNodes
[$node->parent
]->children
= false;
205 $this->_lastIndent
= $node->indent
;
209 } elseif ($this->_lastIndent
> $node->indent
) {
210 // Any block we had going is dead now
211 if ($this->_inBlock
=== true) {
212 $this->_inBlock
= false;
213 if ($this->_blockEnd
= "\n") {
214 $last =& $this->_allNodes
[$this->_lastNode
];
215 $last->data
[key($last->data
)] =
216 trim($last->data
[key($last->data
)]);
220 // We don't know the parent of the node so we have to find it
221 // foreach ($this->_allNodes as $n) {
222 foreach ($this->_indentSort
[$node->indent
] as $n) {
223 if ($n->indent
== $node->indent
) {
224 $node->parent
= $n->parent
;
229 if ($this->_inBlock
=== false) {
230 // Set these properties with information from our current node
231 $this->_lastIndent
= $node->indent
;
233 $this->_lastNode
= $node->id
;
234 // Parse the YAML line and return its data
235 $node->data
= $this->_parseLine($line);
236 // Add the node to the master list
237 $this->_allNodes
[$node->id
] = $node;
238 // Add a reference to the node in an indent array
239 $this->_indentSort
[$node->indent
][] =& $this->_allNodes
[$node->id
];
240 // Add a reference to the node in a References array if this node
241 // has a YAML reference in it.
243 ( (is_array($node->data
)) &&
244 isset($node->data
[key($node->data
)]) &&
245 (!is_array($node->data
[key($node->data
)])) )
247 ( (preg_match('/^&([^ ]+)/',$node->data
[key($node->data
)]))
249 (preg_match('/^\*([^ ]+)/',$node->data
[key($node->data
)])) )
251 $this->_haveRefs
[] =& $this->_allNodes
[$node->id
];
253 ( (is_array($node->data
)) &&
254 isset($node->data
[key($node->data
)]) &&
255 (is_array($node->data
[key($node->data
)])) )
257 // Incomplete reference making code. Ugly, needs cleaned up.
258 foreach ($node->data
[key($node->data
)] as $d) {
259 if ( !is_array($d) &&
260 ( (preg_match('/^&([^ ]+)/',$d))
262 (preg_match('/^\*([^ ]+)/',$d)) )
264 $this->_haveRefs
[] =& $this->_allNodes
[$node->id
];
273 // Here we travel through node-space and pick out references (& and *)
274 $this->_linkReferences();
276 // Build the PHP array out of node-space
277 $trunk = $this->_buildArray();
282 * Dump PHP array to YAML
284 * The dump method, when supplied with an array, will do its best
285 * to convert the array into friendly YAML. Pretty simple. Feel free to
286 * save the returned string as tasteful.yml and pass it around.
288 * Oh, and you can decide how big the indent is and what the wordwrap
289 * for folding is. Pretty cool -- just pass in 'false' for either if
290 * you want to use the default.
292 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
293 * you can turn off wordwrap by passing in 0.
297 * @param array $array PHP array
298 * @param int $indent Pass in false to use the default, which is 2
299 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
301 function dump($array,$indent = false,$wordwrap = false) {
302 // Dumps to some very clean YAML. We'll have to add some more features
303 // and options soon. And better support for folding.
305 // New features and options.
306 if ($indent === false or !is_numeric($indent)) {
307 $this->_dumpIndent
= 2;
309 $this->_dumpIndent
= $indent;
312 if ($wordwrap === false or !is_numeric($wordwrap)) {
313 $this->_dumpWordWrap
= 40;
315 $this->_dumpWordWrap
= $wordwrap;
321 // Start at the base of the array and move through it.
322 foreach ($array as $key => $value) {
323 $string .= $this->_yamlize($key,$value,0);
328 /**** Private Properties ****/
344 /**** Private Methods ****/
347 * Attempts to convert a key / value array item to YAML
350 * @param $key The name of the key
351 * @param $value The value of the item
352 * @param $indent The indent of the current node
354 function _yamlize($key,$value,$indent) {
355 if (is_array($value)) {
356 // It has children. What to do?
357 // Make it the right kind of item
358 $string = $this->_dumpNode($key,NULL,$indent);
360 $indent +
= $this->_dumpIndent
;
362 $string .= $this->_yamlizeArray($value,$indent);
363 } elseif (!is_array($value)) {
364 // It doesn't have children. Yip.
365 $string = $this->_dumpNode($key,$value,$indent);
371 * Attempts to convert an array to YAML
374 * @param $array The array you want to convert
375 * @param $indent The indent of the current level
377 function _yamlizeArray($array,$indent) {
378 if (is_array($array)) {
380 foreach ($array as $key => $value) {
381 $string .= $this->_yamlize($key,$value,$indent);
390 * Find out whether a string needs to be output as a literal rather than in plain style.
391 * Added by Roan Kattouw 13-03-2008
392 * @param $value The string to check
395 function _needLiteral($value) {
396 # Check whether the string contains # or : or begins with any of:
397 # [ - ? , [ ] { } ! * & | > ' " % @ ` ]
398 return (bool)(preg_match("/[#:]/", $value) ||
preg_match("/^[-?,[\]{}!*&|>'\"%@`]/", $value));
402 * Returns YAML from a key and a value
405 * @param $key The name of the key
406 * @param $value The value of the item
407 * @param $indent The indent of the current node
409 function _dumpNode($key,$value,$indent) {
410 // do some folding here, for blocks
411 if (strpos($value,"\n") ||
$this->_needLiteral($value)) {
412 $value = $this->_doLiteralBlock($value,$indent);
414 $value = $this->_doFolding($value,$indent);
417 $spaces = str_repeat(' ',$indent);
421 $string = $spaces.'- '.$value."\n";
424 $string = $spaces.$key.': '.$value."\n";
430 * Creates a literal block for dumping
434 * @param $indent int The value of the indent
436 function _doLiteralBlock($value,$indent) {
437 $exploded = explode("\n",$value);
439 $indent +
= $this->_dumpIndent
;
440 $spaces = str_repeat(' ',$indent);
441 foreach ($exploded as $line) {
442 $newValue .= "\n" . $spaces . trim($line);
448 * Folds a string of text, if necessary
451 * @param $value The string you wish to fold
453 function _doFolding($value,$indent) {
454 // Don't do anything if wordwrap is set to 0
455 if ($this->_dumpWordWrap
=== 0) {
459 if (strlen($value) > $this->_dumpWordWrap
) {
460 $indent +
= $this->_dumpIndent
;
461 $indent = str_repeat(' ',$indent);
462 $wrapped = wordwrap($value,$this->_dumpWordWrap
,"\n$indent");
463 $value = ">\n".$indent.$wrapped;
468 /* Methods used in loading */
471 * Finds and returns the indentation of a YAML line
474 * @param string $line A line from the YAML file
476 function _getIndent($line) {
478 preg_match('/^\s{1,}/',$line,$match);
479 if (!empty($match[0])) {
480 $indent = substr_count($match[0],' ');
488 * Parses YAML code and returns an array for a node
491 * @param string $line A line from the YAML file
493 function _parseLine($line) {
498 if (preg_match('/^-(.*):$/',$line)) {
499 // It's a mapped sequence
500 $key = trim(substr(substr($line,1),0,-1));
502 } elseif ($line[0] == '-' && substr($line,0,3) != '---') {
503 // It's a list item but not a new stream
504 if (strlen($line) > 1) {
505 $value = trim(substr($line,1));
506 // Set the type of the value. Int, string, etc
507 $value = $this->_toType($value);
512 } elseif (preg_match('/^(.+):/',$line,$key)) {
513 // It's a key/value pair most likely
514 // If the key is in double quotes pull it out
516 if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
517 $value = trim(str_replace($matches[1],'',$line));
520 // Do some guesswork as to the key and the value
521 $explode = explode(':',$line);
522 $key = trim($explode[0]);
523 array_shift($explode);
524 $value = trim(implode(':',$explode));
527 // Set the type of the value. Int, string, etc
528 $value = $this->_toType($value);
532 $array[$key] = $value;
539 * Finds the type of the passed value, returns the value as the new type.
541 * @param string $value
544 function _toType($value) {
546 if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
547 $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
548 $value = preg_replace('/\\\\"/','"',$value);
549 } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
552 // Take out strings sequences and mappings
553 $explode = $this->_inlineEscape($matches[1]);
555 // Propogate value array
557 foreach ($explode as $v) {
558 $value[] = $this->_toType($v);
560 } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
562 $array = explode(': ',$value);
563 $key = trim($array[0]);
565 $value = trim(implode(': ',$array));
566 $value = $this->_toType($value);
567 $value = array($key => $value);
568 } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
571 // Take out strings sequences and mappings
572 $explode = $this->_inlineEscape($matches[1]);
574 // Propogate value array
576 foreach ($explode as $v) {
577 $array = $array +
$this->_toType($v);
580 } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
582 } elseif (ctype_digit($value)) {
583 $value = (int)$value;
584 } elseif (in_array(strtolower($value),
585 array('true', 'on', '+', 'yes', 'y'))) {
587 } elseif (in_array(strtolower($value),
588 array('false', 'off', '-', 'no', 'n'))) {
590 } elseif (is_numeric($value)) {
591 $value = (float)$value;
593 // Just a normal string, right?
594 $value = trim(preg_replace('/#(.+)$/','',$value));
601 * Used in inlines to check for more inlines or quoted strings
605 function _inlineEscape($inline) {
606 // There's gotta be a cleaner way to do this...
607 // While pure sequences seem to be nesting just fine,
608 // pure mappings and mappings with sequences inside can't go very
609 // deep. This needs to be fixed.
612 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
614 if (preg_match_all($regex,$inline,$strings)) {
615 $saved_strings[] = $strings[0][0];
616 $inline = preg_replace($regex,'YAMLString',$inline);
620 // Check for sequences
622 if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
623 $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
627 // Check for mappings
629 if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
630 $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
634 $explode = explode(', ',$inline);
636 // Re-add the strings
637 if (!empty($saved_strings)) {
639 foreach ($explode as $key => $value) {
640 if (strpos($value,'YAMLString')) {
641 $explode[$key] = str_replace('YAMLString',$saved_strings[$i],$value);
647 // Re-add the sequences
650 foreach ($explode as $key => $value) {
651 if (strpos($value,'YAMLSeq') !== false) {
652 $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
658 // Re-add the mappings
661 foreach ($explode as $key => $value) {
662 if (strpos($value,'YAMLMap') !== false) {
663 $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
673 * Builds the PHP array from all the YAML nodes we've gathered
677 function _buildArray() {
680 if (!isset($this->_indentSort
[0])) {
684 foreach ($this->_indentSort
[0] as $n) {
685 if (empty($n->parent
)) {
686 $this->_nodeArrayizeData($n);
687 // Check for references and copy the needed data to complete them.
688 $this->_makeReferences($n);
689 // Merge our data with the big array we're building
690 $trunk = $this->_array_kmerge($trunk,$n->data
);
698 * Traverses node-space and sets references (& and *) accordingly
702 function _linkReferences() {
703 if (is_array($this->_haveRefs
)) {
704 foreach ($this->_haveRefs
as $node) {
705 if (!empty($node->data
)) {
706 $key = key($node->data
);
707 // If it's an array, don't check.
708 if (is_array($node->data
[$key])) {
709 foreach ($node->data
[$key] as $k => $v) {
710 $this->_linkRef($node,$key,$k,$v);
713 $this->_linkRef($node,$key);
721 function _linkRef(&$n,$key,$k = NULL,$v = NULL) {
722 if (empty($k) && empty($v)) {
725 if (preg_match('/^&([^ ]+)/',$n->data
[$key],$matches)) {
726 // Flag the node so we know it's a reference
727 $this->_allNodes
[$n->id
]->ref
= substr($matches[0],1);
728 $this->_allNodes
[$n->id
]->data
[$key] =
729 substr($n->data
[$key],strlen($matches[0])+
1);
731 } elseif (preg_match('/^\*([^ ]+)/',$n->data
[$key],$matches)) {
732 $ref = substr($matches[0],1);
733 // Flag the node as having a reference
734 $this->_allNodes
[$n->id
]->refKey
= $ref;
736 } elseif (!empty($k) && !empty($v)) {
737 if (preg_match('/^&([^ ]+)/',$v,$matches)) {
738 // Flag the node so we know it's a reference
739 $this->_allNodes
[$n->id
]->ref
= substr($matches[0],1);
740 $this->_allNodes
[$n->id
]->data
[$key][$k] =
741 substr($v,strlen($matches[0])+
1);
743 } elseif (preg_match('/^\*([^ ]+)/',$v,$matches)) {
744 $ref = substr($matches[0],1);
745 // Flag the node as having a reference
746 $this->_allNodes
[$n->id
]->refKey
= $ref;
752 * Finds the children of a node and aids in the building of the PHP array
754 * @param int $nid The id of the node whose children we're gathering
757 function _gatherChildren($nid) {
759 $node =& $this->_allNodes
[$nid];
760 foreach ($this->_allNodes
as $z) {
761 if ($z->parent
== $node->id
) {
763 $this->_nodeArrayizeData($z);
764 // Check for references
765 $this->_makeReferences($z);
766 // Merge with the big array we're returning
767 // The big array being all the data of the children of our parent node
768 $return = $this->_array_kmerge($return,$z->data
);
775 * Turns a node's data and its children's data into a PHP array
778 * @param array $node The node which you want to arrayize
781 function _nodeArrayizeData(&$node) {
782 if (is_array($node->data
) && $node->children
== true) {
783 // This node has children, so we need to find them
784 $childs = $this->_gatherChildren($node->id
);
785 // We've gathered all our children's data and are ready to use it
786 $key = key($node->data
);
787 $key = empty($key) ?
0 : $key;
788 // If it's an array, add to it of course
789 if (is_array($node->data
[$key])) {
790 $node->data
[$key] = $this->_array_kmerge($node->data
[$key],$childs);
792 $node->data
[$key] = $childs;
794 } elseif (!is_array($node->data
) && $node->children
== true) {
795 // Same as above, find the children of this node
796 $childs = $this->_gatherChildren($node->id
);
797 $node->data
= array();
798 $node->data
[] = $childs;
801 // We edited $node by reference, so just return true
806 * Traverses node-space and copies references to / from this object.
808 * @param object $z A node whose references we wish to make real
811 function _makeReferences(&$z) {
813 if (isset($z->ref
)) {
814 $key = key($z->data
);
815 // Copy the data to this object for easy retrieval later
816 $this->ref
[$z->ref
] =& $z->data
[$key];
817 // It has a reference
818 } elseif (isset($z->refKey
)) {
819 if (isset($this->ref
[$z->refKey
])) {
820 $key = key($z->data
);
821 // Copy the data from this object to make the node a real reference
822 $z->data
[$key] =& $this->ref
[$z->refKey
];
830 * Merges arrays and maintains numeric keys.
832 * An ever-so-slightly modified version of the array_kmerge() function posted
833 * to php.net by mail at nospam dot iaindooley dot com on 2004-04-08.
835 * http://us3.php.net/manual/en/function.array-merge.php#41394
842 function _array_kmerge($arr1,$arr2) {
849 $keys1 = array_keys($arr1);
850 $keys2 = array_keys($arr2);
851 $keys = array_merge($keys1,$keys2);
852 $vals1 = array_values($arr1);
853 $vals2 = array_values($arr2);
854 $vals = array_merge($vals1,$vals2);
857 foreach($keys as $key) {
858 list( /* unused */ ,$val) = each($vals);
859 // This is the good part! If a key already exists, but it's part of a
860 // sequence (an int), just keep addin numbers until we find a fresh one.
861 if (isset($ret[$key]) and is_int($key)) {
862 while (array_key_exists($key, $ret)) {