<?php
include_once('codeGen.php');

/**
 * +++++++++++++++++++ CODE GENERATOR CRUD  ++++++++++++++++++++++
 * 1. Pacote para criação de classes apartir da estrutura de uma
 *    tabela do banco de dados
 * 2. Compativel com PHP 5 ou superior
 * 3. Utilização packages da pear do grupo PHP.net utilizando-se
 *    para conexão de banco de dados a package DB e na utilização
 *    da fonte criada também.
 * 4. Primeiramente foi feito para MySQL
 * 
 * @package CodeGeneratorCRUD
 * @author Rafael Stoever
 * @since 07.2006
 * @version 1.3
 * @copyright rstoever.com 
 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 */

class CodeGeneratorCRUD extends CodeGenerator  {

    public function 
__construct($host$database$user='root'$password=''$soft 'mysql'$debug false) {
        
parent::__construct($host,$database,$user,$password,$soft,$debug);
    }

    public function 
run($strTable "") {
        
$this->cleanVar();
        if (!empty(
$strTable)) {
            
$this->setTable($strTable);
        }
        
$this->debug("(run) Iniciando programa.");
        
$this->getTableStructure();
        
$this->debug("(run) Iniciando a criação do código fonte da classe.");
        
$this->createCode();
        
$this->debug("(run) Finalizado a criação do código fonte da classe.");
        
$this->debug("(run) Gravando arquivo com o fonte da classe.");
        
$this->writeFile($this->_classname.'.class.php'$this->_code);

        
$this->debug("(run) Iniciando a criação do código fonte da classe DB.");
        
$this->createCodeCRUD();
        
$this->debug("(run) Finalizado a criação do código fonte da classe DB.");
        
$this->debug("(run) Gravando arquivo com o fonte da classe DB.");
        
$this->writeFile($this->_classname.'DB.class.php'$this->_code);


    }

    private function 
createCodeCRUD() {
        
$this->_code             = array();
        
$this->_code[] = '<?php';
        
$this->_code[] = '/**';
        
$this->_code[] = ' *  CRUD - Persistencia dos dados da classe '.$this->_classname;
        
$this->_code[] = ' *                    no banco de dados                         ';
        
$this->_code[] = ' * ';
        
$this->_code[] = ' * @since.......: '.date('d.m.Y');
        
$this->_code[] = ' * @autor.......: Rafael Stoever';
        
$this->_code[] = ' * @package.....: '.$this->_classname.'db';
        
$this->_code[] = ' * @subpackage..: '.$this->_classname;
        
$this->_code[] = ' */';
        
$this->_code[] = '';
        
$this->_code[] = 'include("'.strtolower($this->_classname).'.class.php");';
        
$this->_code[] = '';
        
//    2nd) class header
        
$this->_code[] = 'class '.$this->_classname.'db extends '.$this->_classname.' {';
        
$this->_code[] = '';
        
//    3rd) function CrUd - Create or Update table
        
$this->_code[] = '  private $_conn;';
        
$this->_code[] = '  private $_whereSql = "";';
        
$this->_code[] = '  private $_controle = "";';
        
$this->_code[] = '  private $_mensagem = "";';
        
$this->_code[] = '  private $_logTxt   = "";';
        
$this->_code[] = '  private $_debug    = false;';
        
$this->_code[] = '  private $_status   = 0;';
        
$this->_code[] = '  private $_querySQL = "";';
        
$this->_code[] = '  private $_limitIni = 0;';
        
$this->_code[] = '  private $_limitQtde = 0;';
        
$this->_code[] = '  private $_arrSqlRes = array();';
        
$this->_code[] = '';
        
$this->_code[] = ' /**';
        
$this->_code[] = '    * @param object $conn Conexão com o banco de dados (DB.pear.php.net)';
        
$this->_code[] = '    * @param bool clearVariables clearVariables variaveis ao criar o objeto '.$this->_classname.'db (default = true)';
        
$this->_code[] = '    */';
        
$this->_code[] = '  public function __construct($conn,$clearVariables = true) {';
        
$this->_code[] = '    $this->setConn($conn);';
        
$this->_code[] = '    $pai = @get_parent_class($this);';
        
$this->_code[] = '    if (!empty($pai)) {';
        
$this->_code[] = '      if (method_exists($this,ucfirst($pai)) ) {';
        
$this->_code[] = '        call_user_method(ucfirst($pai),$this,$clearVariables);';
        
$this->_code[] = '      }';
        
$this->_code[] = '    }';
        
$this->_code[] = '    $biza = @get_parent_class(@get_parent_class(@get_parent_class($this)));';
        
$this->_code[] = '    if (!empty($biza)) {';
        
$this->_code[] = '      if (method_exists($this,ucfirst($biza)) ) {';
        
$this->_code[] = '        call_user_method(ucfirst($biza),$this,$clearVariables);';
        
$this->_code[] = '      }';
        
$this->_code[] = '    }';
        
$this->_code[] = '    parent::__construct($clearVariables);';
        
$this->_code[] = '    $this->_logTxt = "";';
        
$this->_code[] = '  }';
        
$this->_code[] = '  private function setLogTxt($strLogTxt = "") {';
          
$this->_code[] = '    $this->_logTxt .= htmlspecialchars_decode($strLogTxt."\n", ENT_NOQUOTES);';
        
$this->_code[] = '  }';
        
$this->_code[] = '  public function getLogTxt(){';
          
$this->_code[] = '    return $this->_logTxt;';
        
$this->_code[] = '  }';
        
$this->_code[] = '  ';
        
$this->_code[] = '  private   function setStatus($intStatus = 0) {';
        
$this->_code[] = '    if ($intStatus > 0) {';
        
$this->_code[] = '      $this->_status = 1;';
        
$this->_code[] = '    } else {';
        
$this->_code[] = '      $this->_status = $intStatus;';
        
$this->_code[] = '    }';
        
$this->_code[] = '  }';
        
$this->_code[] = '  public    function getStatus() { return $this->_status; } ';
        
$this->_code[] = '  public    function setConn($conn) { $this->_conn = $conn; }';
        
$this->_code[] = '  protected function getConn() { return $this->_conn; }';
        
$this->_code[] = '  public    function setDebug($boolDebug = false) { ';
        
$this->_code[] = '          if (is_bool($boolDebug)) {';
        
$this->_code[] = '            $this->_debug = $boolDebug;';
        
$this->_code[] = '          } else {';
        
$this->_code[] = '            $this->_debug = false;';
        
$this->_code[] = '          }';
        
$this->_code[] = '  }';
        
$this->_code[] = '  private function getDebug() { return $this->_debug;  }';
        
$this->_code[] = '  public  function setMessage($strClassName,$strObjectName,$strMessage = "") {';
        
$this->_code[] = '      $texto = "<b>Método ".$strObjectName."() da classe ".$strClassName."</b><br>\n";';
        
$this->_code[] = '      $this->_mensagem  = $texto.$strMessage."<br>";';
        
$this->_code[] = '      $this->setLogTxt($strMessage);';
        
$this->_code[] = '  }';
        
$this->_code[] = '  public  function getMessage() {';
        
$this->_code[] = '    if ($this->getDebug()) {';
        
$this->_code[] = '      echo "<FIELDSET style=\'border:1px solid red;background-color:#FFFFCC;color:#3300CC\'>";';
        
$this->_code[] = '      echo "<LEGEND style=\'background-color:#FFFFFF;\'>DEBUG</LEGEND>";';
        
$this->_code[] = '      echo  $this->_mensagem;';
        
$this->_code[] = '      echo "</FIELDSET>";';
        
//        $this->_code[] = '      echo "<div style=\'border:1px solid red;background-color:#FFFFCC;color:#3300CC;margin-top:10px;margin-bottom:10px;\'> \n";';
        //        $this->_code[] = '      echo "<div style=\'position:relative;top:-10px;border:2px solid #000000;width:100px;background-color:#FFFFFF;\'>DEBUG</div>";';
        //        $this->_code[] = '      echo  $this->_mensagem;';
        //        $this->_code[] = '      echo "</div> \n";';
        
$this->_code[] = '    }';
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '  /**';
        
$this->_code[] = '   * Salvar é sobreCarga do metodo da pai fazendo a funcao de salvar nessa classe';
        
$this->_code[] = '   * @param bool $boolThis Indica se é para executar essa função localmente ou ir cascateando até a ultima pai (DEFAULT = false)';
        
$this->_code[] = '   */';
        
$this->_code[] = '  public function salvar($boolThis = false) {';
        
$this->_code[] = '    if (!$boolThis) {';
        
$this->_code[] = '      $biza = @get_parent_class(@get_parent_class(@get_parent_class($this)));';
        
$this->_code[] = '      if (!empty($biza)) {';
        
$this->_code[] = '        if (method_exists($this,"salvar".ucfirst($biza)) ) {';
        
$this->_code[] = '          call_user_method("salvar".ucfirst($biza),$this,$boolThis);';
        
$this->_code[] = '        }';
        
$this->_code[] = '      }';
        
$this->_code[] = '    }';
        
$this->_code[] = '    return $this->salvar'.strtoupper($this->_classname).'();';
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '    // function CrUd - Create or Update table ';
        
$this->_code[] = '    public function salvar'.strtoupper($this->_classname).'() {';
        
$this->_code[] = '      $conn = $this->getConn();';
        
$this->_code[] = '      $sql = "SELECT COUNT(*) C FROM '.strtoupper($this->_tablename).'";';
        
$this->_code[] = '      $this->setControle(0);';
        
$j 0;
        foreach (
$this->_fieldsPrimaryKey as $key => $values) {
            
$this->_code[] = '      $this->setWhere("'.$key.'",$this->getControle());';
            
$j++;
        }
        
$this->_code[] = '      $sql .= $this->getWhereSql();';
        
$this->_code[] = '        $this->executeQuery($sql);';
        
$this->_code[] = '        if ($this->getStatus() >= 0) {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,$sql."<br>rowNum(): ".count($this->getResult()));';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '            $res = $this->getResult();';
        
$this->_code[] = '        } else {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,"Error(".$this->getStatus()."): ".$conn->errorMessage(abs($this->getStatus()))."<br>SQL=".$this->getSQL());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '        }';
        
$this->_code[] = '        $c = (empty($res[0]->c) ? $res[0]->C : $res[0]->c);';
        
$this->_code[] = '    if ($c >= 1) {';
        
$c count($this->_fieldsNamesOriginal);
        
$i 0;
        foreach (
$this->_fieldsNamesOriginal as $field) {
            if (
$i == 0) {
                
$this->_code[] = '      $sql  = "UPDATE '.strtoupper($this->_tablename).' SET                                                                                    ";';
            } else {
                foreach (
$this->_fieldsPrimaryKey as $key) {
                    if (
$key != $field) {
                        
$str '      $sql .= "                         '.$field.'=\'".$this->'.$this->rename($field'get').'()."\'';
                    }
                }
                if ( 
$i == ($c-1)) {
                    
$str .= '          ";';
                    
$this->_code[] = $str;
                    
$this->_code[] = '      $sql .= "                   WHERE ";';
                    
$j 0;
                    foreach (
$this->_fieldsPrimaryKey as $key => $values) {
                        if (
$j == 0) { $and '   '; } else { $and 'AND';}
                        if (
$j < ( count($this->_fieldsPrimaryKey)-)) {
                            
$str '      $sql .= "                     '.$and.' '.strtoupper($key).'          = \'".$this->'.$this->rename($key'get').'()."\'";';
                        } else {
                            
$str '      $sql .= "                     '.$and.' '.strtoupper($key).'          = \'".$this->'.$this->rename($key'get').'()."\';";';
                        }
                        
$this->_code[] = $str;
                        
$j++;
                    }
                } else {
                    
$str .= ',         ";';
                    
$this->_code[] = $str;
                }

            }
            
$i++;
        }
        
$this->_code[] = '    } else {';
        
$i 0;
        foreach (
$this->_fieldsNamesOriginal as $field) {
            
$str '      $sql .= "                      '.$field;
            if (
$i == 0) {
                
$this->_code[] = '      $sql  = "INSERT INTO '.strtoupper($this->_tablename).' (";';
                
$str .= ', ";';
            } elseif (
$i == ($c-1)) {
                
$str .= ') VALUES ( ";';
            } elseif (
$i <= ($c-2)) {
                
$str .= ', ";';
            }
            
$this->_code[] = $str;
            
$i++;
        }
        
$i 0;
        foreach (
$this->_fieldsNames as $field) {
            if ( (
$this->getFieldType($field) != 'int') ) {
              
$str '      $sql .= "                     \'".$this->'.$this->rename($field'get').'()."\'';
            } else {
              
$str '      $sql .= "                      ".$this->'.$this->rename($field'get').'()."';
            }
            if (
$i == ($c-1)) {
                
$str .= '  );";';
            } elseif (
$i <= ($c-2)) {
                
$str .= ', ";';
            }
            
$this->_code[] = $str;
            
$i++;
        }

        
$this->_code[] = '    }';
        
$this->_code[] = '        $this->executeQuery($sql);';
        
$this->_code[] = '        if ($this->getStatus() >= 0) {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,$sql."<br>rowNum(): ".$this->getStatus());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '        } else {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,"Error(".$this->getStatus()."): ".$conn->errorMessage(abs($this->getStatus()))."<br>SQL=".$this->getSQL());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '        }';
        
$this->_code[] = '      return $this->getStatus();';
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '  /**';
        
$this->_code[] = '   * Deletar é sobreCarga do metodo da pai fazendo a funcao de deletar nessa classe';
        
$this->_code[] = '   * @param local Indica se é para executar essa função localmente ou ir cascateando até a ultima pai';
        
$this->_code[] = '   */';
        
$this->_code[] = '  public function delete($boolThis = false) {';
        
$this->_code[] = '    if (!$boolThis) {';
        
$this->_code[] = '      $biza = @get_parent_class(@get_parent_class(@get_parent_class($this)));';
        
$this->_code[] = '      if (!empty($biza)) {';
        
$this->_code[] = '        if (method_exists($this,"deletar".ucfirst($biza)) ) {';
        
$this->_code[] = '          call_user_method("deletar".ucfirst($biza),$this,$local);';
        
$this->_code[] = '        }';
        
$this->_code[] = '      }';
        
$this->_code[] = '    }';
        
$this->_code[] = '    return $this->delete'.strtoupper($this->_classname).'();';
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '  /**';
        
$this->_code[] = '   * @CRUD Delete';
        
$this->_code[] = '   * @return numero de registros alterados';
        
$this->_code[] = '   */';
        
$this->_code[] = ' public function delete'.strtoupper($this->_classname).'() {';
        
$this->_code[] = '    $conn = $this->getConn();';
        
$this->_code[] = '    $sql = "DELETE FROM '.strtoupper($this->_tablename).'";';
        
$this->_code[] = '    $this->setControle(0);';
        foreach (
$this->_fieldsPrimaryKey as $key => $values) {
            
$this->_code[] = '    $this->setWhere("'.$key.'",$this->getControle());';
        }
        
$this->_code[] = '    $sql .= $this->getWhereSql();';
        
$this->_code[] = '        $this->executeQuery($sql);';
        
$this->_code[] = '        if ($this->getStatus() >= 0) {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,$sql."<br>rowNum(): ".$this->getStatus());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '            return $this->getStatus();';
        
$this->_code[] = '        } else {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,"Error(".$this->getStatus()."): ".$conn->errorMessage(abs($this->getStatus()))."<br>SQL=".$this->getSQL());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '            return $this->getStatus();';
        
$this->_code[] = '        }        ';    
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '  private function setControle($ctrl = 0) { ';
        
$this->_code[] = '    $this->_controle = $ctrl;';
        
$this->_code[] = '    if ($ctrl == 0) {';
        
$this->_code[] = '      $this->setWhereSql("");';
        
$this->_code[] = '    }';
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '  private function getControle() { return $this->_controle; }          ';
        
$this->_code[] = '                                                               ';
        
$this->_code[] = '  private function setWhere($campo,$ctrl) {                            ';
        
$this->_code[] = '    $valor = call_user_method("get".$this->rename($campo),$this,"0");          ';
        
$this->_code[] = '    $sql = "";                                                 ';
        
$this->_code[] = '    if (!empty($valor)) {                                      ';
        
$this->_code[] = '      $condicao = " = ";                                       ';
        
$this->_code[] = '      $pos = strpos("-".$valor,">");                           ';
        
$this->_code[] = '      if ($pos == 1) { $condicao = " > ";  }                   ';
        
$this->_code[] = '      $pos = strpos("-".$valor,">=");                          ';
        
$this->_code[] = '      if ($pos == 1) { $condicao = " >= "; }                   ';
        
$this->_code[] = '      $pos = strpos("-".$valor,"<");                           ';
        
$this->_code[] = '      if ($pos == 1) { $condicao = " < ";  }                   ';
        
$this->_code[] = '      $pos = strpos("-".$valor,"<=");                          ';
        
$this->_code[] = '      if ($pos == 1) { $condicao = " <= "; }                   ';
        
$this->_code[] = '      $type = call_user_method("get".$this->rename($campo)."FieldType",$this,"");';
        
$this->_code[] = '      $like = strpos("-".$valor,"%");                          ';
        
$this->_code[] = '      if ($like == 1) {                                        ';
        
$this->_code[] = '        $condicao = " like ";                                  ';
        
$this->_code[] = '      }                                                        ';
        
$this->_code[] = '      if ($ctrl == 0) {                                        ';
        
$this->_code[] = '        $this->setControle(1);                                 ';
        
$this->_code[] = '          if ( ($type == "int") && ($condicao != \' like \') ) {';
        
$this->_code[] = '            $sql =  " WHERE   ".$campo." ".$condicao." ".strtoupper($valor)." ";';
        
$this->_code[] = '          } else {';
        
$this->_code[] = '            $sql =  " WHERE   UPPER(".$campo.") ".$condicao." \'".strtoupper($valor)."\'";';
        
$this->_code[] = '          }';
        
$this->_code[] = '        } else {';
        
$this->_code[] = '          if ( ($type == "int") && ($condicao != \' like \') ) {';
        
$this->_code[] = '            $sql =  " AND     ".$campo." ".$condicao." ".strtoupper($valor)." ";';
        
$this->_code[] = '          } else {';
        
$this->_code[] = '            $sql =  " AND     UPPER(".$campo.") ".$condicao." \'".strtoupper($valor)."\'";';
        
$this->_code[] = '          }';
        
$this->_code[] = '      }                                                        ';
        
$this->_code[] = '    }                                                          ';
        
$this->_code[] = '    $this->setWhereSql($sql);                                  ';
        
$this->_code[] = '  }                                                            ';
        
$this->_code[] = '';
        
$this->_code[] = '    private function setSQL($strSQL) {';
        
$this->_code[] = '        $this->_querySQL = $strSQL;';
        
$this->_code[] = '    }';
        
$this->_code[] = '    private function getSQL(){';
        
$this->_code[] = '        return $this->_querySQL;';
        
$this->_code[] = '    }';
        
$this->_code[] = '';
        
$this->_code[] = '    public function setLimit($intIni = 0, $intQtde = 0) {';
        
$this->_code[] = '        $this->_limitIni = $intIni;';
        
$this->_code[] = '        $this->_limitQtde = $intQtde;';
        
$this->_code[] = '    }';
        
$this->_code[] = '';
        
$this->_code[] = '    private function getLimitQtde(){';
        
$this->_code[] = '        return $this->_limitQtde;';
        
$this->_code[] = '    }';
        
$this->_code[] = '';
        
$this->_code[] = '    private function getLimitIni() {';
        
$this->_code[] = '        return $this->_limitIni;';
        
$this->_code[] = '    }';
        
$this->_code[] = '';
        
$this->_code[] = '    private function setResult($arrResult = array()){';
        
$this->_code[] = '        $this->_arrSqlRes = $arrResult;';
        
$this->_code[] = '    }';
        
$this->_code[] = '    ';
        
$this->_code[] = '    public function getResult(){';
        
$this->_code[] = '        return $this->_arrSqlRes;';
        
$this->_code[] = '    }';
        
$this->_code[] = '';
        
$this->_code[] = '    public function getRowCount(){';
        
$this->_code[] = '      $conn = $this->getConn();';
        
$this->_code[] = '        $sql = "SELECT COUNT(*) C FROM '.strtoupper($this->_tablename).'";';
        
$this->_code[] = '      $this->setControle(0);';
        foreach (
$this->_fieldsNamesOriginal as $field) {
            
$this->_code[] = '      $this->setWhere("'.$field.'",$this->getControle());';
        }
        
$this->_code[] = '      $sql .= $this->getWhereSql();';        
        
$this->_code[] = '        $this->executeQuery($sql);';
        
$this->_code[] = '        if ($this->getStatus() >= 0) {';
        
$this->_code[] = '            $res = $this->getResult();';        
        
$this->_code[] = '            $c = (empty($res[0]->c) ? $res[0]->C : $res[0]->c);';        
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,$sql."<br>rowNum(): ".$c);';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '        } else {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,"Error(".$this->getStatus()."): ".$conn->errorMessage(abs($this->getStatus()))."<br>SQL=".$this->getSQL());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '        }';
        
$this->_code[] = '        return $c;';
        
$this->_code[] = '    }        ';
        
$this->_code[] = '    ';
        
$this->_code[] = '        /**';
        
$this->_code[] = '     * Execute QuerySQL';
        
$this->_code[] = '     *';
        
$this->_code[] = '     * @param string $strSQL  Código SQL';
        
$this->_code[] = '     * @param int $typeResult DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC';
        
$this->_code[] = '     *                               or DB_FETCHMODE_OBJECT';
        
$this->_code[] = '     * @return void';
        
$this->_code[] = '     */';
        
$this->_code[] = '    protected function executeQuery($strSQL = "", $typeResult = DB_FETCHMODE_OBJECT){';
        
$this->_code[] = '        $conn = $this->getConn();';
        
$this->_code[] = '        $this->setResult(array());';
        
$this->_code[] = '        $res = array();';
        
$this->_code[] = '        if (!empty($strSQL)) {';
        
$this->_code[] = '            $this->setSQL($strSQL);';
        
$this->_code[] = '        }';
        
$this->_code[] = '        $strSQL = $this->getSQL();';
        
$this->_code[] = '        if (!empty($strSQL)) {';
        
$this->_code[] = '            if ( ($this->getLimitIni()==0) & ($this->getLimitQtde()==0) ) {';
        
$this->_code[] = '                $result = &$conn->query($this->getSQL());';
        
$this->_code[] = '            } else {';
        
$this->_code[] = '                $result = &$conn->limitQuery($this->getSQL(), $this->getLimitIni(), $this->getLimitQtde());';
        
$this->_code[] = '                $this->setMessage(__CLASS__,__FUNCTION__,$this->getSQL()." LIMIT ".$this->getLimitIni().",".$this->getLimitQtde()."<br><b>Obs.: </b><i>ignore o próximo sql</i>");';
        
$this->_code[] = '                $this->getMessage();';        
        
$this->_code[] = '            }';
        
$this->_code[] = '            if (!DB::isError($result)) {';
        
$this->_code[] = '                if (eregi("select", $this->getSQL()))  {';
        
$this->_code[] = '                  while ($obj =& $result->fetchRow ($typeResult) ) {';
        
$this->_code[] = '                    array_push($res,$obj);';
        
$this->_code[] = '                  }';
        
$this->_code[] = '                }';
        
$this->_code[] = '                $this->setResult($res);';
        
$this->_code[] = '                if (eregi("select", $this->getSQL()))  {';
        
$this->_code[] = '                    $this->setStatus(count($res));';
        
$this->_code[] = '                } else {';
        
$this->_code[] = '                    $this->setStatus($conn->affectedRows());';
        
$this->_code[] = '                }';
        
$this->_code[] = '            } else {';
        
$this->_code[] = '                $this->setStatus(-($conn->errorNative()));';
        
$this->_code[] = '            }';
        
$this->_code[] = '        } else {';
        
$this->_code[] = '            $this->setStatus(-99999);';
        
$this->_code[] = '        }';
        
$this->_code[] = '    }';
        
$this->_code[] = '';
        
$this->_code[] = '  private function getWhereSql() {                                     ';
        
$this->_code[] = '    return $this->_whereSql;                                   ';
        
$this->_code[] = '    $this->_whereSql = "";                                     ';
        
$this->_code[] = '  }                                                            ';
        
$this->_code[] = '                                                               ';
        
$this->_code[] = '  private function setWhereSql($sql = "") {                            ';
        
$this->_code[] = '    if (!empty($sql)) {                                        ';
        
$this->_code[] = '      $this->_whereSql .= $sql;                                ';
        
$this->_code[] = '    } elseif ( (!empty($this->_whereSql)) && ($this->getControle() == 0)) {';
        
$this->_code[] = '      $this->_whereSql =  "";                                  ';
        
$this->_code[] = '    }                                                          ';
        
$this->_code[] = '  }                                                            ';
        
$this->_code[] = '                                                               ';
        
$this->_code[] = '    /**';
        
$this->_code[] = '     * Retrieve in table by primary key field';
        
$this->_code[] = '     * @param int $typeResult DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC';
        
$this->_code[] = '     *                               or DB_FETCHMODE_OBJECT';        
        
$this->_code[] = '     * @return void';
        
$this->_code[] = '     */';
        
$this->_code[] = '     public function consultaKey'.ucfirst($this->_classname).'($camposobrigatorios = true,$typeResult = DB_FETCHMODE_OBJECT) {';
        
$this->_code[] = '       $conn = $this->getConn();';
        
$this->_code[] = '       $sql  = "SELECT * FROM '.strtoupper($this->_tablename).'";';
        
$this->_code[] = '       $this->setControle(0);';
        foreach (
$this->_fieldsPrimaryKey as $key => $values) {
        
$this->_code[] = '       $this->setWhere("'.$key.'",$this->getControle());';
        }
        
$this->_code[] = '         $sql .= $this->getWhereSql();';
        
$this->_code[] = '         $this->executeQuery($sql,$typeResult);';
        
$this->_code[] = '         if ($this->getStatus() >= 0) {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,$sql."<br>rowNum(): ".count($this->getResult()));';
        
$this->_code[] = '            $this->getMessage();            ';
        
$this->_code[] = '            if (count($this->getResult()) == 1) {';
        
$this->_code[] = '                $this->setters'.ucfirst($this->_classname).'($this->getResult(),$camposobrigatorios,$typeResult);';
        
$this->_code[] = '            }';
        
$this->_code[] = '            return $this->getResult();            ';
        
$this->_code[] = '         } else {';
        
$this->_code[] = '            $this->setMessage(__CLASS__,__FUNCTION__,"Error(".$this->getStatus()."): ".$conn->errorMessage(abs($this->getStatus()))."<br>SQL=".$this->getSQL());';
        
$this->_code[] = '            $this->getMessage();';
        
$this->_code[] = '            return $this->getStatus();';
        
$this->_code[] = '         }        ';
        
$this->_code[] = '     }';
        
$this->_code[] = '';
        
$this->_code[] = '    /** function cRud - Retrieve in table with any field by table ';
        
$this->_code[] = '     * ';
        
$this->_code[] = '     * @param boolean $camposobrigatorios (DEFAULT = TRUE) ';
        
$this->_code[] = '     * @param int $typeResult DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC';
        
$this->_code[] = '     *                               or DB_FETCHMODE_OBJECT';                
        
$this->_code[] = '     * @return array ';
        
$this->_code[] = '     */';
        
$this->_code[] = '     public function consulta'.ucfirst($this->_classname).'($camposobrigatorios = true,$typeResult = DB_FETCHMODE_OBJECT) {';
        
$this->_code[] = '       $conn = $this->getConn();';        
        
$this->_code[] = '       $sql  = "SELECT * FROM '.strtoupper($this->_tablename).'";';
        
$this->_code[] = '       $this->setControle(0);';
        foreach (
$this->_fieldsNamesOriginal as $field) {
            
$this->_code[] = '       $this->setWhere("'.$field.'",$this->getControle());';
        }
        
$this->_code[] = '       $sql .= $this->getWhereSql();';
        
$this->_code[] = '       $this->executeQuery($sql,$typeResult);';
        
$this->_code[] = '         if ($this->getStatus() >= 0) {';
        
$this->_code[] = '           $this->setMessage(__CLASS__,__FUNCTION__,$sql."<br>rowNum(): ".count($this->getResult()));';
        
$this->_code[] = '           $this->getMessage();';
        
$this->_code[] = '           if (count($this->getResult()) >= 1) {';
        
$this->_code[] = '             $this->setters'.ucfirst($this->_classname).'($this->getResult(),$camposobrigatorios,$typeResult);';
        
$this->_code[] = '           }';
        
$this->_code[] = '           return $this->getResult();';
        
$this->_code[] = '         } else {';
        
$this->_code[] = '           $this->setMessage(__CLASS__,__FUNCTION__,"Error(".$this->getStatus()."): ".$conn->errorMessage(abs($this->getStatus()))."<br>SQL=".$this->getSQL());';
        
$this->_code[] = '           $this->getMessage();';
        
$this->_code[] = '           return $this->getStatus();';
        
$this->_code[] = '         }';
        
$this->_code[] = '     }';
        
$this->_code[] = '';
        
$this->_code[] = '  /**';
        
$this->_code[] = '   * Função para setar os valores de uma requisição de consulta p/ seus respectivos objetos, uma query do banco';
        
$this->_code[] = '   *';
        
$this->_code[] = '   * @param array|object $res';
        
$this->_code[] = '   * @param bool $camposobrigatorios';
        
$this->_code[] = '   * @param int $typeResult';
        
$this->_code[] = '   */';
        
$this->_code[] = '  private function setters'.ucfirst($this->_classname).'($res,$camposobrigatorios = true,$typeResult = DB_FETCHMODE_OBJECT) {';
        
$this->_code[] = '    for ($i=0;$i<count($res);$i++) {';
        
$this->_code[] = '      if ($typeResult == DB_FETCHMODE_OBJECT) {';
        foreach (
$this->_fieldsNamesOriginal as $field) {
          
$this->_code[] = '        $this->'.$this->rename($field'set').'($res[$i]->'.$field.',"'.$this->isRequired($field,"T","F").'",$i);';
        }
        
$this->_code[] = '      } else {';
        foreach (
$this->_fieldsNamesOriginal as $field) {
          
$this->_code[] = '        $this->'.$this->rename($field'set').'($res[$i][\''.$field.'\'],"'.$this->isRequired($field,"T","F").'",$i);';
        }
        
$this->_code[] = '      }';
        
$this->_code[] = '    }';
        
$this->_code[] = '    $this->setMessage(__CLASS__,__FUNCTION__);';
        
$this->_code[] = '    $this->getMessage();';
        
$this->_code[] = '    if (!$camposobrigatorios) {';
        
$this->_code[] = '      $this->_camposobrigatorios = array();';
        
$this->_code[] = '    }';
        
$this->_code[] = '  }';
        
$this->_code[] = '';
        
$this->_code[] = '  public function display($msg,$msgdb = "msgdb") {';
        
$this->_code[] = '    echo "<div class=\'".$msgdb."\'>";';
        
$this->_code[] = '    if (!empty($msg)) { echo $msg."<br>"; }';
        
$this->_code[] = '    echo "Operação executada em ".date(\'d/m/Y  H:i:s\')."</div>";';
        
$this->_code[] = '  }';


        
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        
$this->_code[] = '}';
        
$this->_code[] = '';
        
$this->_code[] = '/** Esta classe foi gerado automaticamente pelo Code-GenCRUD rstoever.com **/';
        
$this->_code[] = '';
        
$this->_code[] = '?>';
        
$this->_code implode("\n"$this->_code);
        }
}
?>