<?php

/**
 * Template that converts XML files into PHP arrays.
 *
 * See the provided projects/bookstore/runtime-conf.xml file for an example.
 *
 * @author Hans Lellelid <hans@xmpl.org>
 * @version $Revision: 1.2 $
 */
 
 // --------------------------------------------------------------------------------

// Added function_exists check for ticket:244, allowing multiple calls to convert-props
if (!function_exists('simplexml_to_array')) {
/**
 * Converts simplexml object into array, turning attributes into child elements.
 *
 * From a helpful php.net comment.
 * @author Christophe VG
 */ 
function &simplexml_to_array( $xml ) {
	$ar = array();

	foreach( $xml->children() as $k => $v ) {		
		
		// recurse the child
		$child = simplexml_to_array( $v );
		
		//print "Recursed down and found: " . var_export($child, true) . "\n";
		
		// if it's not an array, then it was empty, thus a value/string
		if( count($child) == 0 ) {			
			$child = (string)$v;
		}
	
		// add the childs attributes as if they where children
		foreach( $v->attributes() as $ak => $av ) {
			
			// if the child is not an array, transform it into one
			if( !is_array( $child ) ) {
				$child = array( "value" => $child );
			}

			if ($ak == 'id') {
				// special exception: if there is a key named 'id'
				// then we will name the current key after that id
			    $k = (string) $av;
			} else {
				// otherwise, just add the attribute like a child element
				$child[$ak] = (string) $av;
			}
		}
		
		 // if the $k is already in our children list, we need to transform
		 // it into an array, else we add it as a value
		 if( !in_array( $k, array_keys($ar) ) ) {
			 $ar[$k] = $child;
		 } else {
			 // if the $ar[$k] element is not already an array, then we need to make it one
			 if ( !is_array( $ar[$k] ) ) { $ar[$k] = array( $ar[$k] ); }
			 $ar[$k][] = $child;
		 }
	
	}
	return $ar;
}
} // if (!function_exists...)
 
 // we expect to have:
 //		$propertiesFile - path to properties file.

 $xmlDom = new DOMDocument();
 
 $xmlDom->load($propertiesFile);
 $xml = simplexml_load_string($xmlDom->saveXML());
 
 echo '<' . '?' . "php\n";
 echo "// This file generated by Propel convert-props target on " . strftime("%c") . "\n";
 echo "// from XML runtime conf file " . $pfile->getPath() . "\n";
 echo "return ";
 var_export(simplexml_to_array( $xml ));
 echo ";"; 
