Coverage for Doctrine_Parser_Spyc

Back to coverage report

1 <?php
2   /**
3    * The Simple PHP YAML Class.
4    *
5    * This class can be used to read a YAML file and convert its contents
6    * into a PHP array.  It currently supports a very limited subsection of
7    * the YAML spec.
8    *
9    * Usage:
10    * <code>
11    *   $parser = new Doctrine_Parser_Spyc;
12    *   $array  = $parser->load($file);
13    * </code>
14    * @package Doctrine
15    * @subpackage Spyc
16    */
17   class Doctrine_Parser_Spyc {
18
19     /**
20      * Load YAML into a PHP array statically
21      *
22      * The load method, when supplied with a YAML stream (string or file),
23      * will do its best to convert YAML in a file into a PHP array.  Pretty
24      * simple.
25      *  Usage:
26      *  <code>
27      *   $array = Doctrine_Parser_Spyc::YAMLLoad('lucky.yaml');
28      *   print_r($array);
29      *  </code>
30      * @access public
31      * @return array
32      * @param string $input Path of YAML file or string containing YAML
33      */
34     function YAMLLoad($input) {
35       $spyc = new Doctrine_Parser_Spyc;
36       return $spyc->load($input);
37     }
38
39     /**
40      * Dump YAML from PHP array statically
41      *
42      * The dump method, when supplied with an array, will do its best
43      * to convert the array into friendly YAML.  Pretty simple.  Feel free to
44      * save the returned string as nothing.yaml and pass it around.
45      *
46      * Oh, and you can decide how big the indent is and what the wordwrap
47      * for folding is.  Pretty cool -- just pass in 'false' for either if
48      * you want to use the default.
49      *
50      * Indent's default is 2 spaces, wordwrap's default is 40 characters.  And
51      * you can turn off wordwrap by passing in 0.
52      *
53      * @access public
54      * @return string
55      * @param array $array PHP array
56      * @param int $indent Pass in false to use the default, which is 2
57      * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
58      */
59     function YAMLDump($array,$indent = false,$wordwrap = false) {
60       $spyc = new Doctrine_Parser_Spyc;
61       return $spyc->dump($array,$indent,$wordwrap);
62     }
63
64     /**
65      * Load YAML into a PHP array from an instantiated object
66      *
67      * The load method, when supplied with a YAML stream (string or file path),
68      * will do its best to convert the YAML into a PHP array.  Pretty simple.
69      *  Usage:
70      *  <code>
71      *   $parser = new Doctrine_Parser_Spyc;
72      *   $array  = $parser->load('lucky.yaml');
73      *   print_r($array);
74      *  </code>
75      * @access public
76      * @return array
77      * @param string $input Path of YAML file or string containing YAML
78      */
79     function load($input) {
80       // See what type of input we're talking about
81       // If it's not a file, assume it's a string
82       if ( ! empty($input) && (strpos($input, "\n") === false)
83           && file_exists($input)) {
84         $yaml = file($input);
85       } else {
86         $yaml = explode("\n",$input);
87       }
88       // Initiate some objects and values
89       $base              = new Doctrine_Parser_Spyc_YamlNode (1);
90       $base->indent      = 0;
91       $this->_lastIndent = 0;
92       $this->_lastNode   = $base->id;
93       $this->_inBlock    = false;
94       $this->_isInline   = false;
95       $this->_nodeId     = 2;
96
97       foreach ($yaml as $linenum => $line) {
98         $ifchk = trim($line);
99
100         // If the line starts with a tab (instead of a space), throw a fit.
101         if (preg_match('/^(\t)+(\w+)/', $line)) {
102           $err = 'ERROR: Line '. ($linenum + 1) .' in your input YAML begins'.
103                  ' with a tab.  YAML only recognizes spaces.  Please reformat.';
104           die($err);
105         }
106
107         if ($this->_inBlock === false && empty($ifchk)) {
108           continue;
109         } elseif ($this->_inBlock == true && empty($ifchk)) {
110           $last =& $this->_allNodes[$this->_lastNode];
111           $last->data[key($last->data)] .= "\n";
112         } elseif ($ifchk{0} != '#' && substr($ifchk,0,3) != '---') {
113           // Create a new node and get its indent
114           $node         = new Doctrine_Parser_Spyc_YamlNode ($this->_nodeId);
115   $this->_nodeId++;
116
117           $node->indent = $this->_getIndent($line);
118
119           // Check where the node lies in the hierarchy
120           if ($this->_lastIndent == $node->indent) {
121             // If we're in a block, add the text to the parent's data
122             if ($this->_inBlock === true) {
123               $parent =& $this->_allNodes[$this->_lastNode];
124               $parent->data[key($parent->data)] .= trim($line).$this->_blockEnd;
125             } else {
126               // The current node's parent is the same as the previous node's
127               if (isset($this->_allNodes[$this->_lastNode])) {
128                 $node->parent = $this->_allNodes[$this->_lastNode]->parent;
129               }
130             }
131           } elseif ($this->_lastIndent < $node->indent) {
132             if ($this->_inBlock === true) {
133               $parent =& $this->_allNodes[$this->_lastNode];
134               $parent->data[key($parent->data)] .= trim($line).$this->_blockEnd;
135             } elseif ($this->_inBlock === false) {
136               // The current node's parent is the previous node
137               $node->parent = $this->_lastNode;
138
139               // If the value of the last node's data was > or | we need to
140               // start blocking i.e. taking in all lines as a text value until
141               // we drop our indent.
142               $parent =& $this->_allNodes[$node->parent];
143               $this->_allNodes[$node->parent]->children = true;
144               if (is_array($parent->data)) {
145                 $chk = '';
146                 if (isset ($parent->data[key($parent->data)]))
147                     $chk = $parent->data[key($parent->data)];
148                 if ($chk === '>') {
149                   $this->_inBlock  = true;
150                   $this->_blockEnd = ' ';
151                   $parent->data[key($parent->data)] =
152                         str_replace('>','',$parent->data[key($parent->data)]);
153                   $parent->data[key($parent->data)] .= trim($line).' ';
154                   $this->_allNodes[$node->parent]->children = false;
155                   $this->_lastIndent = $node->indent;
156                 } elseif ($chk === '|') {
157                   $this->_inBlock  = true;
158                   $this->_blockEnd = "\n";
159                   $parent->data[key($parent->data)] =
160                         str_replace('|','',$parent->data[key($parent->data)]);
161                   $parent->data[key($parent->data)] .= trim($line)."\n";
162                   $this->_allNodes[$node->parent]->children = false;
163                   $this->_lastIndent = $node->indent;
164                 }
165               }
166             }
167           } elseif ($this->_lastIndent > $node->indent) {
168             // Any block we had going is dead now
169             if ($this->_inBlock === true) {
170               $this->_inBlock = false;
171               if ($this->_blockEnd = "\n") {
172                 $last =& $this->_allNodes[$this->_lastNode];
173                 $last->data[key($last->data)] =
174                       trim($last->data[key($last->data)]);
175               }
176             }
177
178             // We don't know the parent of the node so we have to find it
179             // foreach ($this->_allNodes as $n) {
180             foreach ($this->_indentSort[$node->indent] as $n) {
181               if ($n->indent == $node->indent) {
182                 $node->parent = $n->parent;
183               }
184             }
185           }
186
187           if ($this->_inBlock === false) {
188             // Set these properties with information from our current node
189             $this->_lastIndent = $node->indent;
190             // Set the last node
191             $this->_lastNode = $node->id;
192             // Parse the YAML line and return its data
193             $node->data = $this->_parseLine($line);
194             // Add the node to the master list
195             $this->_allNodes[$node->id] = $node;
196             // Add a reference to the parent list
197             $this->_allParent[intval($node->parent)][] = $node->id;
198             // Add a reference to the node in an indent array
199             $this->_indentSort[$node->indent][] =& $this->_allNodes[$node->id];
200             // Add a reference to the node in a References array if this node
201             // has a YAML reference in it.
202             if (
203               ( (is_array($node->data)) &&
204                 isset($node->data[key($node->data)]) &&
205                 ( ! is_array($node->data[key($node->data)])) )
206               &&
207               ( (preg_match('/^&([^ ]+)/',$node->data[key($node->data)]))
208                 ||
209                 (preg_match('/^\*([^ ]+)/',$node->data[key($node->data)])) )
210             ) {
211                 $this->_haveRefs[] =& $this->_allNodes[$node->id];
212             } elseif (
213               ( (is_array($node->data)) &&
214                 isset($node->data[key($node->data)]) &&
215                  (is_array($node->data[key($node->data)])) )
216             ) {
217               // Incomplete reference making code.  Ugly, needs cleaned up.
218               foreach ($node->data[key($node->data)] as $d) {
219                 if ( !is_array($d) &&
220                   ( (preg_match('/^&([^ ]+)/',$d))
221                     ||
222                     (preg_match('/^\*([^ ]+)/',$d)) )
223                   ) {
224                     $this->_haveRefs[] =& $this->_allNodes[$node->id];
225                 }
226               }
227             }
228           }
229         }
230       }
231       unset($node);
232
233       // Here we travel through node-space and pick out references (& and *)
234       $this->_linkReferences();
235
236       // Build the PHP array out of node-space
237       $trunk = $this->_buildArray();
238       return $trunk;
239     }
240
241     /**
242      * Dump PHP array to YAML
243      *
244      * The dump method, when supplied with an array, will do its best
245      * to convert the array into friendly YAML.  Pretty simple.  Feel free to
246      * save the returned string as tasteful.yaml and pass it around.
247      *
248      * Oh, and you can decide how big the indent is and what the wordwrap
249      * for folding is.  Pretty cool -- just pass in 'false' for either if
250      * you want to use the default.
251      *
252      * Indent's default is 2 spaces, wordwrap's default is 40 characters.  And
253      * you can turn off wordwrap by passing in 0.
254      *
255      * @access public
256      * @return string
257      * @param array $array PHP array
258      * @param int $indent Pass in false to use the default, which is 2
259      * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
260      */
261     function dump($array,$indent = false,$wordwrap = false) {
262       // Dumps to some very clean YAML.  We'll have to add some more features
263       // and options soon.  And better support for folding.
264
265       // New features and options.
266       if ($indent === false or !is_numeric($indent)) {
267         $this->_dumpIndent = 2;
268       } else {
269         $this->_dumpIndent = $indent;
270       }
271
272       if ($wordwrap === false or !is_numeric($wordwrap)) {
273         $this->_dumpWordWrap = 40;
274       } else {
275         $this->_dumpWordWrap = $wordwrap;
276       }
277
278       // New YAML document
279       $string = "---\n";
280
281       // Start at the base of the array and move through it.
282       foreach ($array as $key => $value) {
283         $string .= $this->_yamlize($key,$value,0);
284       }
285       return $string;
286     }
287
288     /**** Private Properties ****/
289
290     /**#@+
291      * @access private
292      * @var mixed
293      */
294     var $_haveRefs;
295     var $_allNodes;
296     var $_allParent;
297     var $_lastIndent;
298     var $_lastNode;
299     var $_inBlock;
300     var $_isInline;
301     var $_dumpIndent;
302     var $_dumpWordWrap;
303
304     /**#@+*/
305
306     /**** Public Properties ****/
307
308     /**#@+
309      * @access public
310      * @var mixed
311      */
312     var $_nodeId;
313
314     /**#@+*/
315
316     /**** Private Methods ****/
317
318     /**
319      * Attempts to convert a key / value array item to YAML
320      * @access private
321      * @return string
322      * @param $key The name of the key
323      * @param $value The value of the item
324      * @param $indent The indent of the current node
325      */
326     function _yamlize($key,$value,$indent) {
327       if (is_array($value)) {
328         // It has children.  What to do?
329         // Make it the right kind of item
330         $string = $this->_dumpNode($key,NULL,$indent);
331         // Add the indent
332         $indent += $this->_dumpIndent;
333         // Yamlize the array
334         $string .= $this->_yamlizeArray($value,$indent);
335       } elseif ( ! is_array($value)) {
336         // It doesn't have children.  Yip.
337         $string = $this->_dumpNode($key,$value,$indent);
338       }
339       return $string;
340     }
341
342     /**
343      * Attempts to convert an array to YAML
344      * @access private
345      * @return string
346      * @param $array The array you want to convert
347      * @param $indent The indent of the current level
348      */
349     function _yamlizeArray($array,$indent) {
350       if (is_array($array)) {
351         $string = '';
352         foreach ($array as $key => $value) {
353           $string .= $this->_yamlize($key,$value,$indent);
354         }
355         return $string;
356       } else {
357         return false;
358       }
359     }
360
361     /**
362      * Returns YAML from a key and a value
363      * @access private
364      * @return string
365      * @param $key The name of the key
366      * @param $value The value of the item
367      * @param $indent The indent of the current node
368      */
369     function _dumpNode($key,$value,$indent) {
370       // do some folding here, for blocks
371       if (strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false) {
372         $value = $this->_doLiteralBlock($value,$indent);
373       } else {
374         $value  = $this->_doFolding($value,$indent);
375       }
376
377       if (is_bool($value)) {
378         $value = ($value) ? "true" : "false";
379       }
380
381       $spaces = str_repeat(' ',$indent);
382
383       if (is_int($key)) {
384         // It's a sequence
385         $string = $spaces.'- '.$value."\n";
386       } else {
387         // It's mapped
388         $string = $spaces.$key.': '.$value."\n";
389       }
390       return $string;
391     }
392
393     /**
394      * Creates a literal block for dumping
395      * @access private
396      * @return string
397      * @param $value
398      * @param $indent int The value of the indent
399      */
400     function _doLiteralBlock($value,$indent) {
401       $exploded = explode("\n",$value);
402       $newValue = '|';
403       $indent  += $this->_dumpIndent;
404       $spaces   = str_repeat(' ',$indent);
405       foreach ($exploded as $line) {
406         $newValue .= "\n" . $spaces . trim($line);
407       }
408       return $newValue;
409     }
410
411     /**
412      * Folds a string of text, if necessary
413      * @access private
414      * @return string
415      * @param $value The string you wish to fold
416      */
417     function _doFolding($value,$indent) {
418       // Don't do anything if wordwrap is set to 0
419       if ($this->_dumpWordWrap === 0) {
420         return $value;
421       }
422
423       if (strlen($value) > $this->_dumpWordWrap) {
424         $indent += $this->_dumpIndent;
425         $indent = str_repeat(' ',$indent);
426         $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
427         $value   = ">\n".$indent.$wrapped;
428       }
429       return $value;
430     }
431
432     /* Methods used in loading */
433
434     /**
435      * Finds and returns the indentation of a YAML line
436      * @access private
437      * @return int
438      * @param string $line A line from the YAML file
439      */
440     function _getIndent($line) {
441       preg_match('/^\s{1,}/',$line,$match);
442       if ( ! empty($match[0])) {
443         $indent = substr_count($match[0],' ');
444       } else {
445         $indent = 0;
446       }
447       return $indent;
448     }
449
450     /**
451      * Parses YAML code and returns an array for a node
452      * @access private
453      * @return array
454      * @param string $line A line from the YAML file
455      */
456     function _parseLine($line) {
457       $line = trim($line);
458
459       if(!preg_match("/\\\#/", $line)) { 
460         $line = trim(preg_replace('/#.*$/', '', $line)); 
461       }
462
463       $array = array();
464
465       if (preg_match('/^-(.*):$/',$line)) {
466         // It's a mapped sequence
467         $key         = trim(substr(substr($line,1),0,-1));
468         $array[$key] = '';
469       } elseif ($line[0] == '-' && substr($line,0,3) != '---') {
470         // It's a list item but not a new stream
471         if (strlen($line) > 1) {
472           $value   = trim(substr($line,1));
473           // Set the type of the value.  Int, string, etc
474           $value   = $this->_toType($value);
475           $array[] = $value;
476         } else {
477           $array[] = array();
478         }
479       } elseif (preg_match('/^(.+):/',$line,$key)) {
480         // It's a key/value pair most likely
481         // If the key is in double quotes pull it out
482         if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
483           $value = trim(str_replace($matches[1],'',$line));
484           $key   = $matches[2];
485         } else {
486           // Do some guesswork as to the key and the value
487           $explode = explode(':',$line);
488           $key     = trim($explode[0]);
489           array_shift($explode);
490           $value   = trim(implode(':',$explode));
491         }
492
493         // Set the type of the value.  Int, string, etc
494         $value = $this->_toType($value);
495         if (empty($key)) {
496           $array[]     = $value;
497         } else {
498           $array[$key] = $value;
499         }
500       }
501       return $array;
502     }
503
504     /**
505      * Finds the type of the passed value, returns the value as the new type.
506      * @access private
507      * @param string $value
508      * @return mixed
509      */
510     function _toType($value) {
511       if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
512        $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
513        $value = preg_replace('/\\\\"/','"',$value);
514       } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
515         // Inline Sequence
516
517         // Take out strings sequences and mappings
518         $explode = $this->_inlineEscape($matches[1]);
519
520         // Propogate value array
521         $value  = array();
522         foreach ($explode as $v) {
523           $value[] = $this->_toType($v);
524         }
525       } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
526           // It's a map
527           $array = explode(': ',$value);
528           $key   = trim($array[0]);
529           array_shift($array);
530           $value = trim(implode(': ',$array));
531           $value = $this->_toType($value);
532           $value = array($key => $value);
533       } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
534         // Inline Mapping
535
536         // Take out strings sequences and mappings
537         $explode = $this->_inlineEscape($matches[1]);
538
539         // Propogate value array
540         $array = array();
541         foreach ($explode as $v) {
542           $array = $array + $this->_toType($v);
543         }
544         $value = $array;
545       } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
546         $value = NULL;
547       } elseif (preg_match ('/^[0-9]+$/', $value)) {
548       // Cheeky change for compartibility with PHP < 4.2.0
549         $value = (int)$value;
550       } elseif (in_array(strtolower($value),
551                   array('true', 'on', '+', 'yes', 'y'))) {
552         $value = true;
553       } elseif (in_array(strtolower($value),
554                   array('false', 'off', '-', 'no', 'n'))) {
555         $value = false;
556       } elseif (is_numeric($value)) {
557         $value = (float)$value;
558       } else {
559         // Just a normal string, right?
560         $value = trim(preg_replace('/#(.+)$/','',$value));
561       }
562
563       return $value;
564     }
565
566     /**
567      * Used in inlines to check for more inlines or quoted strings
568      * @access private
569      * @return array
570      */
571     function _inlineEscape($inline) {
572       // There's gotta be a cleaner way to do this...
573       // While pure sequences seem to be nesting just fine,
574       // pure mappings and mappings with sequences inside can't go very
575       // deep.  This needs to be fixed.
576
577       $saved_strings = array();
578
579       // Check for strings
580       $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
581       if (preg_match_all($regex,$inline,$strings)) {
582         $saved_strings = $strings[0];
583         $inline  = preg_replace($regex,'YAMLString',$inline);
584       }
585       unset($regex);
586
587       // Check for sequences
588       if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
589         $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
590         $seqs   = $seqs[0];
591       }
592
593       // Check for mappings
594       if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
595         $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
596         $maps   = $maps[0];
597       }
598
599       $explode = explode(', ',$inline);
600
601
602       // Re-add the sequences
603       if ( ! empty($seqs)) {
604         $i = 0;
605         foreach ($explode as $key => $value) {
606           if (strpos($value,'YAMLSeq') !== false) {
607             $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
608             ++$i;
609           }
610         }
611       }
612
613       // Re-add the mappings
614       if ( ! empty($maps)) {
615         $i = 0;
616         foreach ($explode as $key => $value) {
617           if (strpos($value,'YAMLMap') !== false) {
618             $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
619             ++$i;
620           }
621         }
622       }
623
624       // Re-add the strings
625       if ( ! empty($saved_strings)) {
626         $i = 0;
627         foreach ($explode as $key => $value) {
628           while (strpos($value,'YAMLString') !== false) {
629             $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
630             ++$i;
631             $value = $explode[$key];
632           }
633         }
634       }
635
636       return $explode;
637     }
638
639     /**
640      * Builds the PHP array from all the YAML nodes we've gathered
641      * @access private
642      * @return array
643      */
644     function _buildArray() {
645       $trunk = array();
646
647       if ( ! isset($this->_indentSort[0])) {
648         return $trunk;
649       }
650
651       foreach ($this->_indentSort[0] as $n) {
652         if (empty($n->parent)) {
653           $this->_nodeArrayizeData($n);
654           // Check for references and copy the needed data to complete them.
655           $this->_makeReferences($n);
656           // Merge our data with the big array we're building
657           $trunk = $this->_array_kmerge($trunk,$n->data);
658         }
659       }
660
661       return $trunk;
662     }
663
664     /**
665      * Traverses node-space and sets references (& and *) accordingly
666      * @access private
667      * @return bool
668      */
669     function _linkReferences() {
670       if (is_array($this->_haveRefs)) {
671         foreach ($this->_haveRefs as $node) {
672           if ( ! empty($node->data)) {
673             $key = key($node->data);
674             // If it's an array, don't check.
675             if (is_array($node->data[$key])) {
676               foreach ($node->data[$key] as $k => $v) {
677                 $this->_linkRef($node,$key,$k,$v);
678               }
679             } else {
680               $this->_linkRef($node,$key);
681             }
682           }
683         }
684       }
685       return true;
686     }
687
688     function _linkRef(&$n,$key,$k = NULL,$v = NULL) {
689       if (empty($k) && empty($v)) {
690         // Look for &refs
691         if (preg_match('/^&([^ ]+)/',$n->data[$key],$matches)) {
692           // Flag the node so we know it's a reference
693           $this->_allNodes[$n->id]->ref = substr($matches[0],1);
694           $this->_allNodes[$n->id]->data[$key] =
695                    substr($n->data[$key],strlen($matches[0])+1);
696         // Look for *refs
697         } elseif (preg_match('/^\*([^ ]+)/',$n->data[$key],$matches)) {
698           $ref = substr($matches[0],1);
699           // Flag the node as having a reference
700           $this->_allNodes[$n->id]->refKey =  $ref;
701         }
702       } elseif ( ! empty($k) && !empty($v)) {
703         if (preg_match('/^&([^ ]+)/',$v,$matches)) {
704           // Flag the node so we know it's a reference
705           $this->_allNodes[$n->id]->ref = substr($matches[0],1);
706           $this->_allNodes[$n->id]->data[$key][$k] =
707                               substr($v,strlen($matches[0])+1);
708         // Look for *refs
709         } elseif (preg_match('/^\*([^ ]+)/',$v,$matches)) {
710           $ref = substr($matches[0],1);
711           // Flag the node as having a reference
712           $this->_allNodes[$n->id]->refKey =  $ref;
713         }
714       }
715     }
716
717     /**
718      * Finds the children of a node and aids in the building of the PHP array
719      * @access private
720      * @param int $nid The id of the node whose children we're gathering
721      * @return array
722      */
723     function _gatherChildren($nid) {
724       $return = array();
725       $node   =& $this->_allNodes[$nid];
726       if (is_array ($this->_allParent[$node->id])) {
727         foreach ($this->_allParent[$node->id] as $nodeZ) {
728           $z =& $this->_allNodes[$nodeZ];
729           // We found a child
730           $this->_nodeArrayizeData($z);
731           // Check for references
732           $this->_makeReferences($z);
733           // Merge with the big array we're returning
734           // The big array being all the data of the children of our parent node
735           $return = $this->_array_kmerge($return,$z->data);
736         }
737       }
738       return $return;
739     }
740
741     /**
742      * Turns a node's data and its children's data into a PHP array
743      *
744      * @access private
745      * @param array $node The node which you want to arrayize
746      * @return boolean
747      */
748     function _nodeArrayizeData(&$node) {
749       if (is_array($node->data) && $node->children == true) {
750         // This node has children, so we need to find them
751         $childs = $this->_gatherChildren($node->id);
752         // We've gathered all our children's data and are ready to use it
753         $key = key($node->data);
754         $key = empty($key) ? 0 : $key;
755         // If it's an array, add to it of course
756         if (isset ($node->data[$key])) {
757             if (is_array($node->data[$key])) {
758               $node->data[$key] = $this->_array_kmerge($node->data[$key],$childs);
759             } else {
760               $node->data[$key] = $childs;
761             }
762         } else {
763             $node->data[$key] = $childs;
764         }
765       } elseif ( ! is_array($node->data) && $node->children == true) {
766         // Same as above, find the children of this node
767         $childs       = $this->_gatherChildren($node->id);
768         $node->data   = array();
769         $node->data[] = $childs;
770       }
771
772       // We edited $node by reference, so just return true
773       return true;
774     }
775
776     /**
777      * Traverses node-space and copies references to / from this object.
778      * @access private
779      * @param object $z A node whose references we wish to make real
780      * @return bool
781      */
782     function _makeReferences(&$z) {
783       // It is a reference
784       if (isset($z->ref)) {
785         $key                = key($z->data);
786         // Copy the data to this object for easy retrieval later
787         $this->ref[$z->ref] =& $z->data[$key];
788       // It has a reference
789       } elseif (isset($z->refKey)) {
790         if (isset($this->ref[$z->refKey])) {
791           $key           = key($z->data);
792           // Copy the data from this object to make the node a real reference
793           $z->data[$key] =& $this->ref[$z->refKey];
794         }
795       }
796       return true;
797     }
798
799
800     /**
801      * Merges arrays and maintains numeric keys.
802      *
803      * An ever-so-slightly modified version of the array_kmerge() function posted
804      * to php.net by mail at nospam dot iaindooley dot com on 2004-04-08.
805      *
806      * http://us3.php.net/manual/en/function.array-merge.php#41394
807      *
808      * @access private
809      * @param array $arr1
810      * @param array $arr2
811      * @return array
812      */
813     function _array_kmerge($arr1,$arr2) {
814       if( ! is_array($arr1)) $arr1 = array();
815       if( ! is_array($arr2)) $arr2 = array();
816
817       $keys  = array_merge(array_keys($arr1),array_keys($arr2));
818       $vals  = array_merge(array_values($arr1),array_values($arr2));
819       $ret   = array();
820       foreach($keys as $key) {
821         list($unused,$val) = each($vals);
822         if (isset($ret[$key]) and is_int($key)) $ret[] = $val; else $ret[$key] = $val;
823       }
824       return $ret;
825     }
826   }
827 ?>