3 namespace DataAccess\Queries
;
5 use DataAccess\Queries\IQueryBuilder
;
7 class QueryBuilder
implements IQueryBuilder
9 private $_queryString = 'SELECT * FROM %s';
11 protected $_whereClauses = array();
12 protected $_limitClause;
13 protected $_joinClauses = array();
15 public function buildQuery()
17 $this->applyJoinClauses()
21 return $this->_queryString
;
24 public function setBaseQuery($baseQuery)
26 $this->_queryString
= $baseQuery;
29 public function where($columnName, $operator, $value)
31 $this->_whereClauses
[] = array('columnName' => $columnName, 'operator' => $operator, 'value' => $value);
35 public function limit($start, $end = null
)
39 $this->_limitClause
= sprintf(' LIMIT %u,%u', $start, $end);
43 $this->_limitClause
= sprintf(' LIMIT %u', $start);
48 public function join($type, $tableA, $columnA, $tableB, $columnB)
50 $this->_joinClauses
[] = sprintf(' %s JOIN %s ON %s.%s = %s.%s', $type, $tableB, $tableA, $columnA, $tableB, $columnB);
54 public function null($columnName)
56 return $this->where($columnName, 'is', null
);
59 private function applyJoinClauses()
61 foreach($this->_joinClauses
as $joinClause)
63 $this->_queryString
.= $joinClause;
69 private function applyWhereClauses()
71 $this->_queryString
.= ' WHERE ';
73 foreach($this->_whereClauses
as $whereClause)
75 switch(gettype($whereClause['value']))
78 $this->_queryString
.= sprintf("%s%s%u", $whereClause['columnName'], $whereClause['operator'], $whereClause['value']) . ' AND ';
81 $this->_queryString
.= sprintf("%s %s '%s'", $whereClause['columnName'], $whereClause['operator'], $whereClause['value']) . ' AND ';
84 $this->_queryString
.= sprintf("%s is null", $whereClause['columnName']) . ' AND ';
90 $this->_queryString
= rtrim($this->_queryString
, ' AND ');
94 private function applyLimitClause()
96 $this->_queryString
.= $this->_limitClause
;