Completed
Push — master ( 084441...17dbbc )
by Mehmet
03:59
created

SQLQueryBuilder::buildQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
rs 9.6666
cc 2
eloc 6
nc 2
nop 2
crap 2.0185
1
<?php
2
3
namespace Soupmix;
4
5
6
class SQLQueryBuilder extends AbstractQueryBuilder
7
{
8
9
    private $queryBuilder = null;
10
11 2
    public function run(){
12 2
        $this->queryBuilder = $this->getQueryBuilder();
13 2
        $count = $this->getCount();
14 2
        if (!isset($count[0]['total']) || ($count[0]['total']==0)) {
15
            return ['total' => 0, 'data' => null];
16
        }
17 2
        $numberOfRows = $count[0]['total'];
18 2
        $this->setSortOrders();
19 2
        $this->setReturnFields();
20 2
        $this->setOffsetAndLimit();
21 2
        $stmt = $this->soupmix->getConnection()->executeQuery(
22 2
            $this->queryBuilder->getSql(),
23 2
            $this->queryBuilder->getParameters()
24 2
        );
25 2
        $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
26 2
        if($this->distinctFieldName !== null){
27 1
                $numberOfRows = count($result);
28 1
        }
29 2
        return ['total' => $numberOfRows, 'data' => $result];
30
    }
31
32 2
    private function getQueryBuilder()
33
    {
34 2
        if ($this->orFilters !== null){
35 2
            $this->andFilters[] = $this->orFilters;
36 2
        }
37 2
        $this->filters      = $this->andFilters;
38 2
        return $this->buildQuery($this->collection, $this->filters);
39
    }
40
41 2
    private function getCount()
42
    {
43 2
        $queryBuilderCount = clone $this->queryBuilder;
44 2
        $queryBuilderCount->select(" COUNT(*) AS total ");
45 2
        $stmt = $this->soupmix->getConnection()->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters());
46 2
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
47
    }
48
49 2
    private function setSortOrders()
50
    {
51 2
        if ($this->sortFields !== null) {
52
            foreach ($this->sortFields as $sortKey => $sortDir) {
53
                $this->queryBuilder->addOrderBy($sortKey, $sortDir);
54
            }
55
        }
56 2
    }
57
58 2
    private function setReturnFields()
59
    {
60 2
        if ($this->distinctFieldName === null) {
61 2
            $fieldNames = ($this->fieldNames === null) ? "*" : $this->fieldNames;
62 2
            $this->queryBuilder->select($fieldNames);
63 2
            return;
64
        }
65 1
        $this->queryBuilder->select('DISTINCT (`' . $this->distinctFieldName . '`)');
66 1
    }
67
68 2
    private function setOffsetAndLimit()
69
    {
70 2
        $this->queryBuilder->setFirstResult($this->offset)
71 2
            ->setMaxResults($this->limit);
72 2
    }
73
74
75 2
    protected function buildQuery($collection, $filters)
76
    {
77 2
        $queryBuilder = $this->conn->createQueryBuilder();
78 2
        $queryBuilder->from($collection);
79 2
        if ($filters === null) {
80
            return $queryBuilder;
81
        }
82 2
        return $this->buildQueryFilters($queryBuilder, $filters);
83
    }
84
85 2
    protected function buildQueryFilters($queryBuilder, $filters)
86
    {
87 2
        foreach ($filters as $key => $value) {
88 2
            if (strpos($key, '__') === false && is_array($value)) {
89 2
                $queryBuilder = $this->buildQueryForOr($queryBuilder, $value);
90 2
                continue;
91
            }
92 2
            $queryBuilder = $this->buildQueryForAnd($queryBuilder, $key, $value);
93 2
        }
94 2
        return $queryBuilder;
95
    }
96
97 2
    protected function buildQueryForAnd($queryBuilder, $key, $value)
98
    {
99 2
        $sqlOptions = self::buildFilter([$key => $value]);
100 2 View Code Duplication
        if (in_array($sqlOptions['method'], ['in', 'notIn'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
            $queryBuilder->andWhere(
102
                $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
103
            );
104
            return $queryBuilder;
105
        }
106 2
        $queryBuilder->andWhere(
107 2
            '`'.$sqlOptions['key'].'`'
108 2
            . ' ' . $sqlOptions['operand']
109 2
            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
110 2
        );
111 2
        return $queryBuilder;
112
    }
113 2
    protected function buildQueryForOr($queryBuilder, $value)
114
    {
115 2
        $orQuery =[];
116 2
        foreach ($value as $orValue) {
117 2
            $subKey = array_keys($orValue)[0];
118 2
            $subValue = $orValue[$subKey];
119 2
            $sqlOptions = self::buildFilter([$subKey => $subValue]);
120 2 View Code Duplication
            if (in_array($sqlOptions['method'], ['in', 'notIn'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
121 1
                $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value']);
122 1
                continue;
123
            }
124 2
            $orQuery[] =
125 2
                '`'.$sqlOptions['key'].'`'
126 2
                . ' ' . $sqlOptions['operand']
127 2
                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
128
129 2
        }
130 2
        $queryBuilder->andWhere(
131 2
            '(' . implode(' OR ', $orQuery) . ')'
132 2
        );
133 2
        return $queryBuilder;
134
    }
135
136
137 2
    public static function buildFilter($filter)
138
    {
139 2
        $key = array_keys($filter)[0];
140 2
        $value = $filter[$key];
141 2
        $operator = ' = ';
142 2
        $method = 'eq';
143
        $options =[
144 2
            'gte'       => ['method' => 'gte', 'operand' => ' >= '],
145 2
            'gt'        => ['method' => 'gt', 'operand' => ' > '],
146 2
            'lte'       => ['method' => 'lte', 'operand' => ' <= '],
147 2
            'lt'        => ['method' => 'lt', 'operand' => ' < '],
148 2
            'in'        => ['method' => 'in', 'operand' => ' IN '],
149 2
            '!in'       => ['method' => 'notIn', 'operand' => ' NOT IN '],
150 2
            'not'       => ['method' => 'not', 'operand' => ' NOT '],
151 2
            'wildcard'  => ['method' => 'like', 'operand' => ' LIKE '],
152 2
            'prefix'    => ['method' => 'like', 'operand' => ' LIKE '],
153 2
        ];
154 2
        if (strpos($key, '__') !== false) {
155 2
            preg_match('/__(.*?)$/i', $key, $matches);
156 2
            $key        = str_replace($matches[0], '', $key);
157 2
            $queryOperator   = $matches[1];
158 2
            $method     = $options[$queryOperator]['method'];
159 2
            $operator   = $options[$queryOperator]['operand'];
160
            switch ($queryOperator) {
161 2
                case 'wildcard':
162 1
                    $value = '%'.str_replace(array('?', '*'), array('_', '%'), $value).'%';
163 1
                    break;
164 2
                case 'prefix':
165 1
                    $value = $value.'%';
166 1
                    break;
167
            }
168 2
        }
169
        return [
170 2
            'key'       => $key,
171 2
            'operand'   => $operator,
172 2
            'method'    => $method,
173
            'value'     => $value
174 2
        ];
175
    }
176
177
}