<?php
function array_to_object($tab)
{
	$data = new stdClass;
	if (is_array($tab) && !empty($tab) && !isNumericArray($tab))
	{
		foreach ($tab as $key => $val)
		{
			if (is_array($val)){
				$data->$key = array_to_object($val);
			} else {
				$data->$key = $val;
			}
		}
	} else {
		$data = $tab;
	}
	return $data ;
}

function arrayToClass($element, $className)
{
	//file_put_contents('class.log', "class = $className\n", FILE_APPEND);
	$class = new ReflectionClass($className);
	$data = new stdClass;
	foreach ($class->getProperties() as $property)
	{
		if ($property->isPublic() && preg_match_all('/@var\s+([^\s]+)/m', $property->getDocComment(), $matches))
		{
			$name = $property->getName();
            $type = $matches[1][0];
            //file_put_contents('class.log', "property = $name, $type\n", FILE_APPEND);
            //Traitement des types ArrayOf<Type>
            if (substr($type, -2) == '[]') {
            	$type = substr($type, 0, strlen($type)-2);
            	$arrayOf = array();
            	//file_put_contents('class.log', "ArrayOf ".count($element[$name])." elements, $type\n", FILE_APPEND);
            	if (count($element[$name])>0) {
            		foreach($element[$name] as $index => $elementArrayOf){
            			//file_put_contents('class.log', "array = $index, $type\n", FILE_APPEND);
            			if (in_array($type, array('string', 'str', 'float', 'double', 'int', 'integer', 'bool', 'boolean'))){
            				$arrayOf[$index] = $elementArrayOf;
            			} else {
            				$arrayOf[$index] = arrayToClass($elementArrayOf, $type);
            			}
            		}
            	}
            	$data->$name = $arrayOf;
            }
            //Traitement des types complexes
            elseif (class_exists($type))
            {
            	$data->$name = arrayToClass($element[$name], $type);
            }
            // Assignation valeur
            elseif (isset($element[$name]) && !empty($element[$name]))
            {
            	//file_put_contents('class.log', "value = $element[$name]\n", FILE_APPEND);
            	$data->$name = $element[$name];
            }
            // Déclaration element avec valeur par défaut pour ne pas provoquer d'erreur
            else
            {
            	if (in_array($type, array('string', 'str'))){
            		$data->$name = '';
            	} elseif (in_array($type, array('float', 'double', 'int', 'integer'))) {
            		$data->$name = 0;
            	} elseif (in_array($type, array('bool', 'boolean'))) {
            		$data->$name = false;
            	}
            	//file_put_contents('class.log', "value = default\n", FILE_APPEND);
            }
		}
	}
	return $data ;
}

function isNumericArray($tab)
{
	$keys = array_keys($tab);
	if (is_numeric($keys[0])){
		return true;
	} else {
		return false;
	}
}