<?php

class MXMLControls
{
    public $root;
    public $params;

    public function __construct()
    {
    }

    public function loadFile( $xmlFile, $params = NULL)
    {
        libxml_use_internal_errors(true);
        $this->root = simplexml_load_file($xmlFile);
        if (!$this->root)
        {
            foreach (libxml_get_errors() as $error)
            {
                mdump($error);
            }
            libxml_clear_errors();
        }
        $this->params = $params;
    }

    public function loadString( $xmlString, $params = NULL)
    {
        $this->root = simplexml_load_string($xmlString);
        $this->params = $params;
    }

    public function get($nodeName)
    {
        $node = $this->getControlsFromDOM($this->root->$nodeName);
        return $node;
    }

    private function getControlsFromDOM($node)
    {
        $controls = array();
        if ($node)
        {
            foreach($node->children() as $fieldClass=>$n)
            {
                $fi = new $fieldClass;
                $controls[] = $fi;
                $this->getControlFromDOM($fi, $fieldClass, $n);
            }
        }
        return $controls;
    }

    private function getControlFromDOM($field,$c,$node)
    {
        $params = $this->params;
        foreach ($node->attributes() as $k => $v)
        {
            $v = utf8_decode((string)$v);
            if ($k == "id")
            {
                $field->setId($v);
            }
            else if ($k == "method")
            {
                $v = substr(substr($v,2),0,-1);
                eval("{$v};");
            }
            else if (substr($v,0,1) == '$')
            {
                $v = substr(substr($v,2),0,-1);
                $field->$k = eval('return ' . $v .';');
            }
            else
            {
                $field->$k = $v;
            }
        }
        foreach($node->children() as $i=>$v)
        {
            $obj = new $i;       
            $field->addControl($obj);
            $this->getControlFromDOM($obj,$i,$v);
        }
    }
}
?>
