3 * Spyc -- A Simple PHP YAML Class
4 * @version 0.2.3 -- 2006-02-04
5 * @author Chris Wanstrath <chris@ozmm.org>
6 * @link http://spyc.sourceforge.net/
7 * @copyright Copyright 2005-2006 Chris Wanstrath
8 * @license http://www.opensource.org/licenses/mit-license.php MIT License
13 * A node, used by Spyc for parsing YAML.
38 var $children = false;
41 * The constructor assigns the node a unique ID.
46 $this->id
= uniqid('');
51 * The Simple PHP YAML Class.
53 * This class can be used to read a YAML file and convert its contents
54 * into a PHP array. It currently supports a very limited subsection of
60 * $array = $parser->load($file);
67 * Load YAML into a PHP array statically
69 * The load method, when supplied with a YAML stream (string or file),
70 * will do its best to convert YAML in a file into a PHP array. Pretty
74 * $array = Spyc::YAMLLoad('lucky.yml');
79 * @param string $input Path of YAML file or string containing YAML
81 function YAMLLoad($input) {
83 return $spyc->load($input);
87 * Dump YAML from PHP array statically
89 * The dump method, when supplied with an array, will do its best
90 * to convert the array into friendly YAML. Pretty simple. Feel free to
91 * save the returned string as nothing.yml and pass it around.
93 * Oh, and you can decide how big the indent is and what the wordwrap
94 * for folding is. Pretty cool -- just pass in 'false' for either if
95 * you want to use the default.
97 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
98 * 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 public static 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.yml');
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
;
139 $this->_lastIndent
= 0;
140 $this->_lastNode
= $base->id
;
141 $this->_inBlock
= false;
142 $this->_isInline
= false;
144 foreach ($yaml as $linenum => $line) {
145 $ifchk = trim($line);
147 // If the line starts with a tab (instead of a space), throw a fit.
148 if (preg_match('/^(\t)+(\w+)/', $line)) {
149 $err = 'ERROR: Line '. ($linenum +
1) .' in your input YAML begins'.
150 ' with a tab. YAML only recognizes spaces. Please reformat.';
154 if ($this->_inBlock
=== false && empty($ifchk)) {
156 } elseif ($this->_inBlock
== true && empty($ifchk)) {
157 $last =& $this->_allNodes
[$this->_lastNode
];
158 $last->data
[key($last->data
)] .= "\n";
159 } elseif ($ifchk{0} != '#' && substr($ifchk,0,3) != '---') {
160 // Create a new node and get its indent
161 $node = new YAMLNode
;
162 $node->indent
= $this->_getIndent($line);
164 // Check where the node lies in the hierarchy
165 if ($this->_lastIndent
== $node->indent
) {
166 // If we're in a block, add the text to the parent's data
167 if ($this->_inBlock
=== true) {
168 $parent =& $this->_allNodes
[$this->_lastNode
];
169 $parent->data
[key($parent->data
)] .= trim($line).$this->_blockEnd
;
171 // The current node's parent is the same as the previous node's
172 if (isset($this->_allNodes
[$this->_lastNode
])) {
173 $node->parent
= $this->_allNodes
[$this->_lastNode
]->parent
;
176 } elseif ($this->_lastIndent
< $node->indent
) {
177 if ($this->_inBlock
=== true) {
178 $parent =& $this->_allNodes
[$this->_lastNode
];
179 $parent->data
[key($parent->data
)] .= trim($line).$this->_blockEnd
;
180 } elseif ($this->_inBlock
=== false) {
181 // The current node's parent is the previous node
182 $node->parent
= $this->_lastNode
;
184 // If the value of the last node's data was > or | we need to
185 // start blocking i.e. taking in all lines as a text value until
186 // we drop our indent.
187 $parent =& $this->_allNodes
[$node->parent
];
188 $this->_allNodes
[$node->parent
]->children
= true;
189 if (is_array($parent->data
)) {
190 $chk = $parent->data
[key($parent->data
)];
192 $this->_inBlock
= true;
193 $this->_blockEnd
= ' ';
194 $parent->data
[key($parent->data
)] =
195 str_replace('>','',$parent->data
[key($parent->data
)]);
196 $parent->data
[key($parent->data
)] .= trim($line).' ';
197 $this->_allNodes
[$node->parent
]->children
= false;
198 $this->_lastIndent
= $node->indent
;
199 } elseif ($chk === '|') {
200 $this->_inBlock
= true;
201 $this->_blockEnd
= "\n";
202 $parent->data
[key($parent->data
)] =
203 str_replace('|','',$parent->data
[key($parent->data
)]);
204 $parent->data
[key($parent->data
)] .= trim($line)."\n";
205 $this->_allNodes
[$node->parent
]->children
= false;
206 $this->_lastIndent
= $node->indent
;
210 } elseif ($this->_lastIndent
> $node->indent
) {
211 // Any block we had going is dead now
212 if ($this->_inBlock
=== true) {
213 $this->_inBlock
= false;
214 if ($this->_blockEnd
= "\n") {
215 $last =& $this->_allNodes
[$this->_lastNode
];
216 $last->data
[key($last->data
)] =
217 trim($last->data
[key($last->data
)]);
221 // We don't know the parent of the node so we have to find it
222 // foreach ($this->_allNodes as $n) {
223 foreach ($this->_indentSort
[$node->indent
] as $n) {
224 if ($n->indent
== $node->indent
) {
225 $node->parent
= $n->parent
;
230 if ($this->_inBlock
=== false) {
231 // Set these properties with information from our current node
232 $this->_lastIndent
= $node->indent
;
234 $this->_lastNode
= $node->id
;
235 // Parse the YAML line and return its data
236 $node->data
= $this->_parseLine($line);
237 // Add the node to the master list
238 $this->_allNodes
[$node->id
] = $node;
239 // Add a reference to the node in an indent array
240 $this->_indentSort
[$node->indent
][] =& $this->_allNodes
[$node->id
];
241 // Add a reference to the node in a References array if this node
242 // has a YAML reference in it.
244 ( (is_array($node->data
)) &&
245 isset($node->data
[key($node->data
)]) &&
246 (!is_array($node->data
[key($node->data
)])) )
248 ( (preg_match('/^&([^ ]+)/',$node->data
[key($node->data
)]))
250 (preg_match('/^\*([^ ]+)/',$node->data
[key($node->data
)])) )
252 $this->_haveRefs
[] =& $this->_allNodes
[$node->id
];
254 ( (is_array($node->data
)) &&
255 isset($node->data
[key($node->data
)]) &&
256 (is_array($node->data
[key($node->data
)])) )
258 // Incomplete reference making code. Ugly, needs cleaned up.
259 foreach ($node->data
[key($node->data
)] as $d) {
260 if ( !is_array($d) &&
261 ( (preg_match('/^&([^ ]+)/',$d))
263 (preg_match('/^\*([^ ]+)/',$d)) )
265 $this->_haveRefs
[] =& $this->_allNodes
[$node->id
];
274 // Here we travel through node-space and pick out references (& and *)
275 $this->_linkReferences();
277 // Build the PHP array out of node-space
278 $trunk = $this->_buildArray();
283 * Dump PHP array to YAML
285 * The dump method, when supplied with an array, will do its best
286 * to convert the array into friendly YAML. Pretty simple. Feel free to
287 * save the returned string as tasteful.yml and pass it around.
289 * Oh, and you can decide how big the indent is and what the wordwrap
290 * for folding is. Pretty cool -- just pass in 'false' for either if
291 * you want to use the default.
293 * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
294 * you can turn off wordwrap by passing in 0.
298 * @param array $array PHP array
299 * @param int $indent Pass in false to use the default, which is 2
300 * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
302 function dump($array,$indent = false,$wordwrap = false) {
303 // Dumps to some very clean YAML. We'll have to add some more features
304 // and options soon. And better support for folding.
306 // New features and options.
307 if ($indent === false or !is_numeric($indent)) {
308 $this->_dumpIndent
= 2;
310 $this->_dumpIndent
= $indent;
313 if ($wordwrap === false or !is_numeric($wordwrap)) {
314 $this->_dumpWordWrap
= 40;
316 $this->_dumpWordWrap
= $wordwrap;
322 // Start at the base of the array and move through it.
323 foreach ($array as $key => $value) {
324 $string .= $this->_yamlize($key,$value,0);
329 /**** Private Properties ****/
345 /**** Private Methods ****/
348 * Attempts to convert a key / value array item to YAML
351 * @param $key The name of the key
352 * @param $value The value of the item
353 * @param $indent The indent of the current node
355 function _yamlize($key,$value,$indent) {
356 if (is_array($value)) {
357 // It has children. What to do?
358 // Make it the right kind of item
359 $string = $this->_dumpNode($key,NULL,$indent);
361 $indent +
= $this->_dumpIndent
;
363 $string .= $this->_yamlizeArray($value,$indent);
364 } elseif (!is_array($value)) {
365 // It doesn't have children. Yip.
366 $string = $this->_dumpNode($key,$value,$indent);
372 * Attempts to convert an array to YAML
375 * @param $array The array you want to convert
376 * @param $indent The indent of the current level
378 function _yamlizeArray($array,$indent) {
379 if (is_array($array)) {
381 foreach ($array as $key => $value) {
382 $string .= $this->_yamlize($key,$value,$indent);
391 * Returns YAML from a key and a value
394 * @param $key The name of the key
395 * @param $value The value of the item
396 * @param $indent The indent of the current node
398 function _dumpNode($key,$value,$indent) {
399 // do some folding here, for blocks
400 if (strpos($value,"\n")) {
401 $value = $this->_doLiteralBlock($value,$indent);
403 $value = $this->_doFolding($value,$indent);
406 $spaces = str_repeat(' ',$indent);
410 $string = $spaces.'- '.$value."\n";
413 $string = $spaces.$key.': '.$value."\n";
419 * Creates a literal block for dumping
423 * @param $indent int The value of the indent
425 function _doLiteralBlock($value,$indent) {
426 $exploded = explode("\n",$value);
428 $indent +
= $this->_dumpIndent
;
429 $spaces = str_repeat(' ',$indent);
430 foreach ($exploded as $line) {
431 $newValue .= "\n" . $spaces . trim($line);
437 * Folds a string of text, if necessary
440 * @param $value The string you wish to fold
442 function _doFolding($value,$indent) {
443 // Don't do anything if wordwrap is set to 0
444 if ($this->_dumpWordWrap
=== 0) {
448 if (strlen($value) > $this->_dumpWordWrap
) {
449 $indent +
= $this->_dumpIndent
;
450 $indent = str_repeat(' ',$indent);
451 $wrapped = wordwrap($value,$this->_dumpWordWrap
,"\n$indent");
452 $value = ">\n".$indent.$wrapped;
457 /* Methods used in loading */
460 * Finds and returns the indentation of a YAML line
463 * @param string $line A line from the YAML file
465 function _getIndent($line) {
467 preg_match('/^\s{1,}/',$line,$match);
468 if (!empty($match[0])) {
469 $indent = substr_count($match[0],' ');
477 * Parses YAML code and returns an array for a node
480 * @param string $line A line from the YAML file
482 function _parseLine($line) {
487 if (preg_match('/^-(.*):$/',$line)) {
488 // It's a mapped sequence
489 $key = trim(substr(substr($line,1),0,-1));
491 } elseif ($line[0] == '-' && substr($line,0,3) != '---') {
492 // It's a list item but not a new stream
493 if (strlen($line) > 1) {
494 $value = trim(substr($line,1));
495 // Set the type of the value. Int, string, etc
496 $value = $this->_toType($value);
501 } elseif (preg_match('/^(.+):/',$line,$key)) {
502 // It's a key/value pair most likely
503 // If the key is in double quotes pull it out
505 if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
506 $value = trim(str_replace($matches[1],'',$line));
509 // Do some guesswork as to the key and the value
510 $explode = explode(':',$line);
511 $key = trim($explode[0]);
512 array_shift($explode);
513 $value = trim(implode(':',$explode));
516 // Set the type of the value. Int, string, etc
517 $value = $this->_toType($value);
521 $array[$key] = $value;
528 * Finds the type of the passed value, returns the value as the new type.
530 * @param string $value
533 function _toType($value) {
535 if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
536 $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
537 $value = preg_replace('/\\\\"/','"',$value);
538 } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
541 // Take out strings sequences and mappings
542 $explode = $this->_inlineEscape($matches[1]);
544 // Propogate value array
546 foreach ($explode as $v) {
547 $value[] = $this->_toType($v);
549 } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
551 $array = explode(': ',$value);
552 $key = trim($array[0]);
554 $value = trim(implode(': ',$array));
555 $value = $this->_toType($value);
556 $value = array($key => $value);
557 } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
560 // Take out strings sequences and mappings
561 $explode = $this->_inlineEscape($matches[1]);
563 // Propogate value array
565 foreach ($explode as $v) {
566 $array = $array +
$this->_toType($v);
569 } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
571 } elseif (ctype_digit($value)) {
572 $value = (int)$value;
573 } elseif (in_array(strtolower($value),
574 array('true', 'on', '+', 'yes', 'y'))) {
576 } elseif (in_array(strtolower($value),
577 array('false', 'off', '-', 'no', 'n'))) {
579 } elseif (is_numeric($value)) {
580 $value = (float)$value;
582 // Just a normal string, right?
583 $value = trim(preg_replace('/#(.+)$/','',$value));
590 * Used in inlines to check for more inlines or quoted strings
594 function _inlineEscape($inline) {
595 // There's gotta be a cleaner way to do this...
596 // While pure sequences seem to be nesting just fine,
597 // pure mappings and mappings with sequences inside can't go very
598 // deep. This needs to be fixed.
601 $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
603 if (preg_match_all($regex,$inline,$strings)) {
604 $saved_strings[] = $strings[0][0];
605 $inline = preg_replace($regex,'YAMLString',$inline);
609 // Check for sequences
611 if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
612 $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
616 // Check for mappings
618 if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
619 $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
623 $explode = explode(', ',$inline);
625 // Re-add the strings
626 if (!empty($saved_strings)) {
628 foreach ($explode as $key => $value) {
629 if (strpos($value,'YAMLString')) {
630 $explode[$key] = str_replace('YAMLString',$saved_strings[$i],$value);
636 // Re-add the sequences
639 foreach ($explode as $key => $value) {
640 if (strpos($value,'YAMLSeq') !== false) {
641 $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
647 // Re-add the mappings
650 foreach ($explode as $key => $value) {
651 if (strpos($value,'YAMLMap') !== false) {
652 $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
662 * Builds the PHP array from all the YAML nodes we've gathered
666 function _buildArray() {
669 if (!isset($this->_indentSort
[0])) {
673 foreach ($this->_indentSort
[0] as $n) {
674 if (empty($n->parent
)) {
675 $this->_nodeArrayizeData($n);
676 // Check for references and copy the needed data to complete them.
677 $this->_makeReferences($n);
678 // Merge our data with the big array we're building
679 $trunk = $this->_array_kmerge($trunk,$n->data
);
687 * Traverses node-space and sets references (& and *) accordingly
691 function _linkReferences() {
692 if (is_array($this->_haveRefs
)) {
693 foreach ($this->_haveRefs
as $node) {
694 if (!empty($node->data
)) {
695 $key = key($node->data
);
696 // If it's an array, don't check.
697 if (is_array($node->data
[$key])) {
698 foreach ($node->data
[$key] as $k => $v) {
699 $this->_linkRef($node,$key,$k,$v);
702 $this->_linkRef($node,$key);
710 function _linkRef(&$n,$key,$k = NULL,$v = NULL) {
711 if (empty($k) && empty($v)) {
714 if (preg_match('/^&([^ ]+)/',$n->data
[$key],$matches)) {
715 // Flag the node so we know it's a reference
716 $this->_allNodes
[$n->id
]->ref
= substr($matches[0],1);
717 $this->_allNodes
[$n->id
]->data
[$key] =
718 substr($n->data
[$key],strlen($matches[0])+
1);
720 } elseif (preg_match('/^\*([^ ]+)/',$n->data
[$key],$matches)) {
721 $ref = substr($matches[0],1);
722 // Flag the node as having a reference
723 $this->_allNodes
[$n->id
]->refKey
= $ref;
725 } elseif (!empty($k) && !empty($v)) {
726 if (preg_match('/^&([^ ]+)/',$v,$matches)) {
727 // Flag the node so we know it's a reference
728 $this->_allNodes
[$n->id
]->ref
= substr($matches[0],1);
729 $this->_allNodes
[$n->id
]->data
[$key][$k] =
730 substr($v,strlen($matches[0])+
1);
732 } elseif (preg_match('/^\*([^ ]+)/',$v,$matches)) {
733 $ref = substr($matches[0],1);
734 // Flag the node as having a reference
735 $this->_allNodes
[$n->id
]->refKey
= $ref;
741 * Finds the children of a node and aids in the building of the PHP array
743 * @param int $nid The id of the node whose children we're gathering
746 function _gatherChildren($nid) {
748 $node =& $this->_allNodes
[$nid];
749 foreach ($this->_allNodes
as $z) {
750 if ($z->parent
== $node->id
) {
752 $this->_nodeArrayizeData($z);
753 // Check for references
754 $this->_makeReferences($z);
755 // Merge with the big array we're returning
756 // The big array being all the data of the children of our parent node
757 $return = $this->_array_kmerge($return,$z->data
);
764 * Turns a node's data and its children's data into a PHP array
767 * @param array $node The node which you want to arrayize
770 function _nodeArrayizeData(&$node) {
771 if (is_array($node->data
) && $node->children
== true) {
772 // This node has children, so we need to find them
773 $childs = $this->_gatherChildren($node->id
);
774 // We've gathered all our children's data and are ready to use it
775 $key = key($node->data
);
776 $key = empty($key) ?
0 : $key;
777 // If it's an array, add to it of course
778 if (is_array($node->data
[$key])) {
779 $node->data
[$key] = $this->_array_kmerge($node->data
[$key],$childs);
781 $node->data
[$key] = $childs;
783 } elseif (!is_array($node->data
) && $node->children
== true) {
784 // Same as above, find the children of this node
785 $childs = $this->_gatherChildren($node->id
);
786 $node->data
= array();
787 $node->data
[] = $childs;
790 // We edited $node by reference, so just return true
795 * Traverses node-space and copies references to / from this object.
797 * @param object $z A node whose references we wish to make real
800 function _makeReferences(&$z) {
802 if (isset($z->ref
)) {
803 $key = key($z->data
);
804 // Copy the data to this object for easy retrieval later
805 $this->ref
[$z->ref
] =& $z->data
[$key];
806 // It has a reference
807 } elseif (isset($z->refKey
)) {
808 if (isset($this->ref
[$z->refKey
])) {
809 $key = key($z->data
);
810 // Copy the data from this object to make the node a real reference
811 $z->data
[$key] =& $this->ref
[$z->refKey
];
819 * Merges arrays and maintains numeric keys.
821 * An ever-so-slightly modified version of the array_kmerge() function posted
822 * to php.net by mail at nospam dot iaindooley dot com on 2004-04-08.
824 * http://us3.php.net/manual/en/function.array-merge.php#41394
831 function _array_kmerge($arr1,$arr2) {
838 $keys1 = array_keys($arr1);
839 $keys2 = array_keys($arr2);
840 $keys = array_merge($keys1,$keys2);
841 $vals1 = array_values($arr1);
842 $vals2 = array_values($arr2);
843 $vals = array_merge($vals1,$vals2);
846 foreach($keys as $key) {
847 list( /* unused */ ,$val) = each($vals);
848 // This is the good part! If a key already exists, but it's part of a
849 // sequence (an int), just keep addin numbers until we find a fresh one.
850 if (isset($ret[$key]) and is_int($key)) {
851 while (array_key_exists($key, $ret)) {