Fix bug in query builder that stopped multiple where clauses being run on the same...
[rock.divinelegy.git] / DataAccess / Queries / QueryConstraints.php
1 <?php
2
3 namespace DataAccess\Queries;
4
5 use DataAccess\Queries\IQueryConstraints;
6
7 class QueryConstraints implements IQueryConstraints
8 {
9 private $_queryString;
10
11 protected $_whereClauses = array();
12 protected $_limitClause;
13 protected $_joinClause;
14
15 public function applyTo($queryString)
16 {
17 $this->_queryString = $queryString;
18
19 $this->applyJoinClause()
20 ->applyWhereClauses()
21 ->applyLimitClause();
22
23 return $this->_queryString;
24 }
25
26 public function where($columnName, $operator, $value)
27 {
28 $this->_whereClauses[$columnName] = array('operator' => $operator, 'value' => $value);
29 return $this;
30 }
31
32 public function limit($start, $end = null)
33 {
34 if($end)
35 {
36 $this->_limitClause = sprintf(' LIMIT %u,%u', $start, $end);
37 return $this;
38 }
39
40 $this->_limitClause = sprintf(' LIMIT %u', $start);
41
42 return $this;
43 }
44
45 public function join($type, $tableA, $columnA, $tableB, $columnB)
46 {
47 $this->_joinClause = sprintf(' %s JOIN %s ON %s.%s = %s.%s', $type, $tableB, $tableA, $columnA, $tableB, $columnB);
48 return $this;
49 }
50
51 private function applyJoinClause()
52 {
53 $this->_queryString .= $this->_joinClause;
54 return $this;
55 }
56
57 private function applyWhereClauses()
58 {
59 $this->_queryString .= ' WHERE ';
60
61 foreach($this->_whereClauses as $columnName => $columnValue)
62 {
63 switch(gettype($columnValue['value']))
64 {
65 case 'integer':
66 $this->_queryString .= sprintf("%s%s%u", $columnName, $columnValue['operator'], $columnValue['value']) . ' AND ';
67 break;
68 case 'string':
69 $this->_queryString .= sprintf("%s %s '%s'", $columnName, $columnValue['operator'], $columnValue['value']) . ' AND ';
70 break;
71 }
72
73 }
74
75 $this->_queryString = rtrim($this->_queryString, ' AND ');
76 return $this;
77 }
78
79 private function applyLimitClause()
80 {
81 $this->_queryString .= $this->_limitClause;
82 return $this;
83 }
84
85 }