Better DI for database.
[rock.divinelegy.git] / DataAccess / Queries / QueryBuilder.php
1 <?php
2
3 namespace DataAccess\Queries;
4
5 use DataAccess\Queries\IQueryBuilder;
6
7 class QueryBuilder implements IQueryBuilder
8 {
9 private $_queryString = 'SELECT * FROM %s';
10
11 protected $_whereClauses = array();
12 protected $_limitClause;
13 protected $_joinClauses = array();
14
15 public function buildQuery()
16 {
17 $this->applyJoinClauses()
18 ->applyWhereClauses()
19 ->applyLimitClause();
20
21 return $this->_queryString;
22 }
23
24 public function setBaseQuery($baseQuery)
25 {
26 $this->_queryString = $baseQuery;
27 }
28
29 public function where($columnName, $operator, $value)
30 {
31 $this->_whereClauses[$columnName] = array('operator' => $operator, 'value' => $value);
32 return $this;
33 }
34
35 public function limit($start, $end = null)
36 {
37 if($end)
38 {
39 $this->_limitClause = sprintf(' LIMIT %u,%u', $start, $end);
40 return $this;
41 }
42
43 $this->_limitClause = sprintf(' LIMIT %u', $start);
44
45 return $this;
46 }
47
48 public function join($type, $tableA, $columnA, $tableB, $columnB)
49 {
50 $this->_joinClauses[] = sprintf(' %s JOIN %s ON %s.%s = %s.%s', $type, $tableB, $tableA, $columnA, $tableB, $columnB);
51 return $this;
52 }
53
54 private function applyJoinClauses()
55 {
56 foreach($this->_joinClauses as $joinClause)
57 {
58 $this->_queryString .= $joinClause;
59 }
60
61 return $this;
62 }
63
64 private function applyWhereClauses()
65 {
66 $this->_queryString .= ' WHERE ';
67
68 foreach($this->_whereClauses as $columnName => $columnValue)
69 {
70 switch(gettype($columnValue['value']))
71 {
72 case 'integer':
73 $this->_queryString .= sprintf("%s%s%u", $columnName, $columnValue['operator'], $columnValue['value']) . ' AND ';
74 break;
75 case 'string':
76 $this->_queryString .= sprintf("%s %s '%s'", $columnName, $columnValue['operator'], $columnValue['value']) . ' AND ';
77 break;
78 }
79
80 }
81
82 $this->_queryString = rtrim($this->_queryString, ' AND ');
83 return $this;
84 }
85
86 private function applyLimitClause()
87 {
88 $this->_queryString .= $this->_limitClause;
89 return $this;
90 }
91
92 }