1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Soupmix; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class SQLQueryBuilder extends AbstractQueryBuilder |
7
|
|
|
{ |
8
|
|
|
|
9
|
1 |
|
public function run(){ |
10
|
1 |
|
$this->andFilters[]= $this->orFilters; |
11
|
1 |
|
$this->filters = $this->andFilters; |
12
|
1 |
|
$queryBuilder = $this->soupmix->buildQuery($this->collection, $this->filters); |
13
|
1 |
|
$queryBuilderCount = clone $queryBuilder; |
14
|
1 |
|
$queryBuilderCount->select(" COUNT(*) AS total "); |
15
|
1 |
|
$stmt = $this->soupmix->getConnection()->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters()); |
16
|
1 |
|
$count = $stmt->fetchAll(\PDO::FETCH_ASSOC); |
17
|
1 |
|
$numberOfSet = 0; |
18
|
1 |
|
if (isset($count[0]['total']) && ($count[0]['total']>0)) { |
19
|
1 |
|
$numberOfSet = $count[0]['total']; |
20
|
1 |
|
if ($this->sortFields !== null) { |
21
|
|
|
$params['sort'] = ''; |
|
|
|
|
22
|
|
View Code Duplication |
foreach ($this->sortFields as $sort_key => $sort_dir) { |
|
|
|
|
23
|
|
|
if ($params['sort']!='') { |
24
|
|
|
$params['sort'] .= ','; |
25
|
|
|
} |
26
|
|
|
$queryBuilder->addOrderBy($sort_key, $sort_dir); |
27
|
|
|
} |
28
|
|
|
} |
29
|
1 |
|
if ($this->distinctFieldName === null) { |
30
|
1 |
|
$fieldNames = ($this->fieldNames === null) ? "*" : $this->fieldNames; |
31
|
1 |
|
$queryBuilder->select($fieldNames) |
32
|
1 |
|
->setFirstResult($this->offset) |
33
|
1 |
|
->setMaxResults($this->limit); |
34
|
1 |
|
} |
35
|
|
|
else { |
36
|
1 |
|
$queryBuilder->select('DISTINCT (`' . $this->distinctFieldName . '`)'); |
37
|
|
|
} |
38
|
1 |
|
$stmt = $this->soupmix->getConnection()->executeQuery($queryBuilder->getSql(), $queryBuilder->getParameters()); |
39
|
1 |
|
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC); |
40
|
1 |
|
if($this->distinctFieldName !== null){ |
41
|
1 |
|
$numberOfSet = count($result); |
42
|
1 |
|
} |
43
|
1 |
|
} |
44
|
1 |
|
return ['total' => $numberOfSet, 'data' => $result]; |
|
|
|
|
45
|
|
|
} |
46
|
|
|
} |
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.