Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Where
- {
- public $operation = 'AND';
- public $condition = '';
- public $childs = [];
- public $params = [];
- static private $DBH = NULL;
- /**
- * Where constructor.
- * If $condition is string, all next parameters
- * @param $condition
- */
- public function __construct($condition)
- {
- //get DBH for escaping string
- if(empty(self::$DBH) && empty((self::$DBH = DBHandler::getHandler())))
- return NULL;
- if(is_string($condition))
- {
- $this->condition = $condition;
- $this->params = array_slice(func_get_args(),1);
- }
- elseif(is_array($condition))
- {
- if(array_key_exists('condition',$condition) &&
- array_key_exists('values',$condition))
- {
- $this->condition = $condition['condition'];
- $this->params = $condition['values'];
- }
- foreach ($condition as $k => $c)
- if(is_string($k))
- {
- if ($k == 'operation')
- $this->operation = $c;
- else
- $this->childs[] = new self($k, $c);
- }
- elseif(is_array($c))
- $this->childs[] = new self($c);
- }
- else
- {
- foreach(func_get_args() as $a)
- $this->childs[] = new self($a);
- }
- }
- /**
- * Getter-setter for operation
- * @param null|string $o Operation
- * @return string|Where
- */
- public function operation($o = NULL)
- {
- if(empty($o))
- return $this->operation;
- else
- {
- $this->operation = $o;
- return $this;
- }
- }
- /**
- * Get finally condition from
- * @return string
- */
- public function get_condition()
- {
- return $this->update_condition(!empty($this->condition));
- }
- /**
- * Regenerate where-condition string with all child conditions
- * @param bool $inchilds
- * @return string
- */
- private function update_condition($inchilds=false)
- {
- if($inchilds)
- {
- return '('.implode(' '.$this->operation.' ',array_map(function(/** @var $x Where*/$x){return $x->get_condition();},$this->childs)).')';
- }
- else
- {
- $c = explode('?',$this->condition);
- $r = ''; $c1 = count($c); $c2 = count($this->params);
- for($i = 0, $j = 0; $i < $c1; $i++)
- {
- $r .= $c[$i];
- if($j < $c2 && $i < $c1-1)
- {
- $r .= self::$DBH->_escape($this->params[$j]);
- $j++;
- if($j == $c2)
- $j = 0;
- }
- }
- return $r;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement