|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Soupmix; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
class SQLQueryBuilder extends AbstractQueryBuilder |
|
7
|
|
|
{ |
|
8
|
|
|
|
|
9
|
|
|
private $queryBuilder; |
|
10
|
|
|
|
|
11
|
2 |
|
public function run(){ |
|
12
|
2 |
|
$this->queryBuilder = $this->getQueryBuilder(); |
|
13
|
2 |
|
$count = $this->getCount(); |
|
14
|
2 |
|
$numberOfRows = 0; |
|
15
|
2 |
|
$result = null; |
|
16
|
2 |
|
if (isset($count[0]['total']) && ($count[0]['total']>0)) { |
|
17
|
2 |
|
$numberOfRows = $count[0]['total']; |
|
18
|
2 |
|
$this->setSortOrders(); |
|
19
|
2 |
|
$this->setReturnFields(); |
|
20
|
2 |
|
$this->setOffsetAndLimit(); |
|
21
|
2 |
|
$stmt = $this->soupmix->getConnection() |
|
22
|
2 |
|
->executeQuery( |
|
23
|
2 |
|
$this->queryBuilder->getSql(), |
|
24
|
2 |
|
$this->queryBuilder->getParameters() |
|
25
|
2 |
|
); |
|
26
|
2 |
|
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC); |
|
27
|
2 |
|
if($this->distinctFieldName !== null){ |
|
28
|
1 |
|
$numberOfRows = count($result); |
|
29
|
1 |
|
} |
|
30
|
2 |
|
} |
|
31
|
2 |
|
return ['total' => $numberOfRows, 'data' => $result]; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
2 |
|
private function getQueryBuilder() |
|
35
|
|
|
{ |
|
36
|
2 |
|
if ($this->orFilters !== null){ |
|
37
|
2 |
|
$this->andFilters[] = $this->orFilters; |
|
38
|
2 |
|
} |
|
39
|
2 |
|
$this->filters = $this->andFilters; |
|
40
|
2 |
|
return $this->soupmix->buildQuery($this->collection, $this->filters); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
2 |
|
private function getCount() |
|
44
|
|
|
{ |
|
45
|
2 |
|
$queryBuilderCount = clone $this->queryBuilder; |
|
46
|
2 |
|
$queryBuilderCount->select(" COUNT(*) AS total "); |
|
47
|
2 |
|
$stmt = $this->soupmix->getConnection()->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters()); |
|
48
|
2 |
|
return $stmt->fetchAll(\PDO::FETCH_ASSOC); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
private function setSortOrders() |
|
52
|
|
|
{ |
|
53
|
2 |
|
if ($this->sortFields !== null) { |
|
54
|
|
|
foreach ($this->sortFields as $sortKey => $sortDir) { |
|
55
|
|
|
$this->queryBuilder->addOrderBy($sortKey, $sortDir); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
2 |
|
} |
|
59
|
|
|
|
|
60
|
2 |
|
private function setReturnFields() |
|
61
|
|
|
{ |
|
62
|
2 |
|
if ($this->distinctFieldName === null) { |
|
63
|
2 |
|
$fieldNames = ($this->fieldNames === null) ? "*" : $this->fieldNames; |
|
64
|
2 |
|
$this->queryBuilder->select($fieldNames); |
|
65
|
2 |
|
return; |
|
66
|
|
|
} |
|
67
|
1 |
|
$this->queryBuilder->select('DISTINCT (`' . $this->distinctFieldName . '`)'); |
|
68
|
1 |
|
} |
|
69
|
|
|
|
|
70
|
2 |
|
private function setOffsetAndLimit() |
|
71
|
|
|
{ |
|
72
|
2 |
|
$this->queryBuilder->setFirstResult($this->offset) |
|
73
|
2 |
|
->setMaxResults($this->limit); |
|
74
|
|
|
} |
|
75
|
|
|
} |