<?php

class DB_where{ //함수가 같은 값이 들어올때는 ? 대신 적용하는걸 생각해야 한다.
  public $where_obj;

  public function __construct( $com="and" ){
    $this->where_obj = new stdClass();
    $this->where_obj->com = $com;
    $this->where_obj->row = array();
    switch( $com ){
      case "and":
        $this->add("1=?",1); break;
      case "or":
        $this->add("1<>?",1); break;
    }
  }

  public function add($qry, $val="EMPTY"){
    if( is_array($val) ){
      foreach( $val as $v ){
        $this->where_obj->row[] = array("qry"=>$qry,"val"=>$v);
      }
    }else{
      $this->where_obj->row[] = array("qry"=>$qry,"val"=>$val);
    }
  }

  public function sub_where($com){
    $sub_where = new DB_where($com);
    $this->where_obj->row[] = $sub_where;
    return $sub_where;
  }

  public function get_where(){
    $qryrow = array();
    $valrow = array();
    foreach( (array)$this->where_obj->row as $wval ){
      if( is_object($wval) ){
        $subs = $wval->get_where();
        $qryrow[] = "( {$subs['qry']} )";
        $valrow = array_merge($valrow, $subs['val']);
      }else{
        if( $wval['val'] == "EMPTY" ) {
          $qryrow[] = "{$wval['qry']}";
        }else{
          if ($this->chkeval($wval['val'])) {
            $qryrow[] = str_replace("?", $this->valeval($wval['val']), $wval['qry']);
          } else {
            $qryrow[] = "{$wval['qry']}";
            array_push($valrow, $wval['val']);
          }
        }
      }
    }
    return array(
      'qry' => implode( " {$this->where_obj->com} ", $qryrow ),
      'val' => $valrow,
    );
  }

  public function sqleval($str){
    return chr(27).$str;
  }

  public function chkeval($str){
    if( preg_match("/^".chr(27)."/ims",$str) ){
      return true;
    }
    return false;
  }

  public function valeval($str,$val=""){
    return preg_replace("/^".chr(27)."/ims",$val,$str);
  }
}