56a82dc9986270e25dce5386b786d6759fc50246
[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[] = array('columnName' => $columnName, '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 public function null($columnName)
55 {
56 return $this->where($columnName, 'is', null);
57 }
58
59 private function applyJoinClauses()
60 {
61 foreach($this->_joinClauses as $joinClause)
62 {
63 $this->_queryString .= $joinClause;
64 }
65
66 return $this;
67 }
68
69 private function applyWhereClauses()
70 {
71 $this->_queryString .= ' WHERE ';
72
73 foreach($this->_whereClauses as $whereClause)
74 {
75 switch(gettype($whereClause['value']))
76 {
77 case 'integer':
78 $this->_queryString .= sprintf("%s%s%u", $whereClause['columnName'], $whereClause['operator'], $whereClause['value']) . ' AND ';
79 break;
80 case 'string':
81 $this->_queryString .= sprintf("%s %s '%s'", $whereClause['columnName'], $whereClause['operator'], $whereClause['value']) . ' AND ';
82 break;
83 case 'NULL':
84 $this->_queryString .= sprintf("%s is null", $whereClause['columnName']) . ' AND ';
85 break;
86 }
87
88 }
89
90 $this->_queryString = rtrim($this->_queryString, ' AND ');
91 return $this;
92 }
93
94 private function applyLimitClause()
95 {
96 $this->_queryString .= $this->_limitClause;
97 return $this;
98 }
99
100 }