<?php
class Easy_Db_Select{
	protected $where;
	protected function __select(){
		$this->flush();
	}
	protected function __from(){
		$numargs = func_num_args();
		if($numargs>0){
			$args = func_get_arg(0);
			if (isset($args[1])){
				if(is_array($args[1]) === false){	//是数组则切割
					$fields = explode(',', $args[1]);
				}else{
					$fields = $args[1];
				}
				$field = '';
				foreach($fields as $key){
					$field.= $field ? ','. $key : $key;
				}
				$this->Raws['select'] = 'SELECT '.$field;
			}else{
				$this->Raws['select'] = 'SELECT * ';
			}
			if (is_Array($args[0]) === true){
				$this->Raws['from'] = ' FROM `'.implode('`,`', $args[0]).'`';
			}else{
				$this->Raws['from'] = ' FROM '.$args[0];
			}
		}
		return $this;
	}
	protected function __where(){
		$args = func_get_arg(0);
		if($args[0]){
			if ( empty($this->Raws['where']) === true ){
				$this->Raws['where'] = '';
				$this->Raws['where'] = ' WHERE 1=1';
			}
			if(is_array($args[0]) === true){
				foreach($args[0] as $key=>$value){
					//echo $this->Raws['where'];
					$this->Raws['where'].=  ' AND `'.$key.'` = \''.$value.'\'';
				}
			}else{
				$this->Raws['where'].= ' AND ' . $args[0];
			}
		}
		return $this;
	}
	protected function __join(){
		$args = func_get_arg(0);
		$array = explode(' ' , $this->Raws['from']);
		$lastable = end($array);
		if ($args[2]) {
			$this->Raws['select'].= ','.$args[2];
		}	
		$this->Raws['from'] = $this->Raws['from'] .' LEFT JOIN '.$args[0].' ON '. $args[1];
		return $this;
		
	}
	protected function __rjoin(){
		$args = func_get_arg(0);
		$array = explode(' ' , $this->Raws['from']);
		$lastable = end($array);
		if ($args[2]) {
			$this->Raws['select'].= ','.$args[2];
		}	
		$this->Raws['from'] = $this->Raws['from'] .' RIGHT JOIN '.$args[0].' ON '. $args[1];
		return $this;
		
	}
	protected function __group(){
		$args = func_get_arg(0);
		if (strlen($this->Raws['group']) <4){
			$this->Raws['group'] = ' GROUP BY ' .$args[0];
		}else{
			$this->Raws['group'] = $this->Raws['group']. ', '. $args[0];
		}
		return $this;
	}
	protected function __flush(){
		unset($this->Raws);
	}
	protected function __order(){
		$args = func_get_arg(0);
		if ($args[0]){
			if (empty($this->Raws['order']) === true){
				$this->Raws['order'] = ' ORDER BY ' .$args[0];
			}else{
				$this->Raws['order'] = ', '. $args[0];
			}
		}return $this;
	}
	protected function __limit(){
		$args = func_get_arg(0);
		if (is_null($args[0]) === false ){
			$this->Raws['limit'] = ' LIMIT '.implode(',', $args);
		}
		return $this;
	}
	public  function __toString(){
		if(is_array($this->Raws)){
			$sql = implode($this->Raws);
			//unset($this->Raws);
			//print_r($this->Raws);
			return $sql;
		}
	}
	public function __call($method, $args){
		$func = '__'.$method;
		//echo $func;
		if(method_exists($this, $func) === false){
			exit('调用了无效的类方法名:'.$method.'<br>错误行数:'.__LINE__.'<br>错误文件'.__FILE__);
		}else{
			return $this->$func($args);
		}
	}
}