<?php

class Vframe_Form
{
  private
    
$_bInit false,
    
$_aFields = array(),
    
$_aValues = array(),
    
$_aErrors = array();
  
  public function 
__construct(array $aFields)
  {
    foreach(
$aFields as $oElement)
      
$this->_field($oElement);
  }
  
  protected function 
_field(Vframe_Form_Element $oElement)
  {
    
$sElement $oElement->name();
    
    if(isset(
$this->_aFields[$sElement]))
      throw new 
Vframe_Form_Exception('Field "' $sElement '" arleady exists!');
    
    
$this->_aFields[$sElement] = $oElement;
  }
  
  public function 
init()
  {
    if(!
count($this->_aFields))
      throw new 
Vframe_Form_Exception('Cannot initialize empty former! Add at least one field.');
    
    
$this->_bInit true;
    
    foreach(
$this->_aFields as $sField => $oField)
    {
      
$aField $oField->execute();
      
      
$this->_aValues[$sField] = $aField['value'];
      
      if(
$aField['error'])
        
$this->_aErrors[$sField] = $aField['error'];
    }
  }
  
  public function 
error($sField null)
  {
    if(
$sField)
      return isset(
$this->_aErrors[$sField]) ? $this->_aErrors[$sField] : null;
    
    return 
count($this->_aErrors);
  }
  
  public function 
__get($sField)
  {
    if(!
$this->_bInit)
      throw new 
Vframe_Form_Exception('Cannot get value of field "' $sField '" before initialization!');
    
    if(!isset(
$this->_aFields[$sField]))
      throw new 
Vframe_Form_Exception('Cannot get value from unknown field "' $sField '"!');
    
    return 
$this->_aValues[$sField];
  }
}

?>