Completed
Push — master ( c4f500...65ebe1 )
by Mehmet
03:13 queued 33s
created

SQLQueryBuilder::run()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
ccs 0
cts 17
cp 0
rs 8.9197
cc 4
eloc 17
nc 3
nop 0
crap 20
1
<?php
2
3
namespace Soupmix;
4
5
class SQLQueryBuilder extends AbstractQueryBuilder
6
{
7
8
    private $queryBuilder;
9
10
    public function run()
11
    {
12
        $this->queryBuilder = $this->getQueryBuilder();
13
        $this->setJoins();
14
        $count = $this->getCount();
15
        if (!isset($count[0]['total']) || ($count[0]['total']===0)) {
16
            return ['total' => 0, 'data' => null];
17
        }
18
        $numberOfRows = $count[0]['total'];
19
        $this->setSortOrders();
20
        $this->setOffsetAndLimit();
21
        $this->setReturnFields();
22
        $stmt = $this->conn->executeQuery(
23
            $this->queryBuilder->getSql(),
24
            $this->queryBuilder->getParameters()
25
        );
26
        $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
27
        if ($this->distinctFieldName !== null) {
28
                $numberOfRows = count($result);
29
        }
30
        return ['total' => $numberOfRows, 'data' => $result];
31
    }
32
33
    private function getQueryBuilder()
34
    {
35
        if ($this->orFilters !== null) {
36
            $this->andFilters[] = $this->orFilters;
37
        }
38
        $this->filters      = $this->andFilters;
39
        return $this->buildQuery($this->collection, $this->filters);
40
    }
41
42
    private function getCount()
43
    {
44
        $queryBuilderCount = clone $this->queryBuilder;
45
        $queryBuilderCount->select(' COUNT(*) AS total ');
46
        $stmt = $this->conn->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters());
47
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
48
    }
49
50
    private function setSortOrders()
51
    {
52
        if ($this->sortFields !== null) {
53
            foreach ($this->addAlias($this->sortFields) as $sortKey => $sortDir) {
0 ignored issues
show
Bug introduced by
The expression $this->addAlias($this->sortFields) of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
54
                $this->queryBuilder->addOrderBy($sortKey, $sortDir);
55
            }
56
        }
57
    }
58
59
    private function setJoins()
60
    {
61
        $this->setJoinsForType('innerJoin');
62
        $this->setJoinsForType('leftJoin');
63
        $this->setJoinsForType('rightJoin');
64
        $this->setJoinsForType('outerJoin');
65
    }
66
67
    private function setJoinsForType($joinType)
68
    {
69
        if ($this->{$joinType} === null) {
70
            return;
71
        }
72
        foreach ($this->{$joinType} as $collectionName => $collection) {
73
            $fieldNames = $this->addAlias($collection['returnFields'], $collectionName);
74
            $this->returnFieldsForJoin($fieldNames);
0 ignored issues
show
Bug introduced by
It seems like $fieldNames defined by $this->addAlias($collect...lds'], $collectionName) on line 73 can also be of type string; however, Soupmix\SQLQueryBuilder::returnFieldsForJoin() does only seem to accept null|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
75
            $joinCondition = '';
76
            foreach ($collection['relations'] as $relation) {
77
                $joinCondition .= empty($joinCondition) ? '':' AND ';
78
                $relationType = array_keys($relation)[0];
79
                $source = array_keys($relation[$relationType])[0];
80
                $condition = $collectionName . '.' . $source
81
                    . ' = ' . $this->collection . '.' . $relation[$relationType][$source];
82
                if ($relationType != 'field') {
83
                    $condition = $collectionName . '.' . $source . ' '
84
                        . $relationType . ' '. $relation[$relationType][$source];
85
                }
86
                $joinCondition .= $condition;
87
            }
88
            $this->queryBuilder->{$joinType}($this->collection, $collectionName, $collectionName, $joinCondition);
89
        }
90
        return $this;
91
    }
92
    public function returnFieldsForJoin(array $fieldNames = null)
93
    {
94
        if ($fieldNames !== null) {
95
            foreach ($fieldNames as $fieldName) {
96
                $this->fieldNames[] = $fieldName;
97
            }
98
        }
99
    }
100
101
    private function setReturnFields()
102
    {
103
        if ($this->distinctFieldName === null) {
104
            $fieldNames = ($this->fieldNames === null)
105
                ? $this->addAlias('*')
106
                : $this->addAlias($this->fieldNames);
107
            $this->queryBuilder->select($fieldNames);
108
            return;
109
        }
110
        $this->queryBuilder->select('DISTINCT (`' . $this->collection . '`.`' . $this->distinctFieldName . '`)');
111
    }
112
113
    private function setOffsetAndLimit()
114
    {
115
        $this->queryBuilder->setFirstResult($this->offset)
116
            ->setMaxResults($this->limit);
117
    }
118
119
    private function addAlias($fields, $collection = null)
120
    {
121
        $collection = (!is_null($collection)) ? $collection : $this->collection;
122
        if (!is_array($fields)) {
123
            return  $collection . '.' . $fields;
124
        }
125
        if (!is_array($fields)) {
126
            return  $collection . '.' . $fields;
127
        }
128
        $newFields = [];
129
        foreach ($fields as $field => $value) {
130
            if (strpos($value, '.')!== false) {
131
                $newFields[] = $value;
132
                continue;
133
            }
134
            if (is_int($field)) {
135
                if (!is_array($fields)) {
136
                    $newFields[] = $collection . '.' . $fields;
137
                    continue;
138
                }
139
                $newFields[] = $collection . '.' . $value;
140
                continue;
141
            }
142
            $newFields[$collection.'.'.$field] = $value;
143
        }
144
        return $newFields;
145
    }
146
147
    protected function buildQuery($collection, $filters)
148
    {
149
        $queryBuilder = $this->conn->createQueryBuilder();
150
        $queryBuilder->from($collection, $collection);
151
        if ($filters === null) {
152
            return $queryBuilder;
153
        }
154
        return $this->buildQueryFilters($queryBuilder, $filters);
155
    }
156
157
    protected function buildQueryFilters($queryBuilder, $filters)
158
    {
159
        foreach ($filters as $key => $value) {
160
            if (is_array($value) && strpos($key, '__') === false) {
161
                $queryBuilder = $this->buildQueryForOr($queryBuilder, $value);
162
                continue;
163
            }
164
            $queryBuilder = $this->buildQueryForAnd($queryBuilder, $key, $value);
165
        }
166
        return $queryBuilder;
167
    }
168
169
    protected function buildQueryForAnd($queryBuilder, $key, $value)
170
    {
171
        $sqlOptions = self::buildFilter([$key => $value]);
172 View Code Duplication
        if (in_array($sqlOptions['method'], ['in', 'notIn'], true)) {
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...
173
            $queryBuilder->andWhere(
174
                $queryBuilder->expr()->{$sqlOptions['method']}(
175
                    $this->collection . '.' . $sqlOptions['key'], $sqlOptions['value']
176
                )
177
            );
178
            return $queryBuilder;
179
        }
180
        $queryBuilder->andWhere(
181
            '`' . $this->collection . '`.`' . $sqlOptions['key'].'`'
182
            . ' ' . $sqlOptions['operand']
183
            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
184
        );
185
        return $queryBuilder;
186
    }
187
    protected function buildQueryForOr($queryBuilder, $value)
188
    {
189
        $orQuery =[];
190
        foreach ($value as $orValue) {
191
            $subKey = array_keys($orValue)[0];
192
            $subValue = $orValue[$subKey];
193
            $sqlOptions = self::buildFilter([$subKey => $subValue]);
194 View Code Duplication
            if (in_array($sqlOptions['method'], ['in', 'notIn'], true)) {
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...
195
                $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}(
196
                    $this->collection . '.' . $sqlOptions['key'], $sqlOptions['value']
197
                );
198
                continue;
199
            }
200
            $orQuery[] =
201
                '`' . $this->collection . '`.`' . $sqlOptions['key'].'`'
202
                . ' ' . $sqlOptions['operand']
203
                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
204
        }
205
        $queryBuilder->andWhere(
206
            '(' . implode(' OR ', $orQuery) . ')'
207
        );
208
        return $queryBuilder;
209
    }
210
211
212
    public static function buildFilter($filter)
213
    {
214
        $key = array_keys($filter)[0];
215
        $value = $filter[$key];
216
        $operator = ' = ';
217
        $method = 'eq';
218
        $options =[
219
            'gte'       => ['method' => 'gte', 'operand' => ' >= '],
220
            'gt'        => ['method' => 'gt', 'operand' => ' > '],
221
            'lte'       => ['method' => 'lte', 'operand' => ' <= '],
222
            'lt'        => ['method' => 'lt', 'operand' => ' < '],
223
            'in'        => ['method' => 'in', 'operand' => ' IN '],
224
            '!in'       => ['method' => 'notIn', 'operand' => ' NOT IN '],
225
            'not'       => ['method' => 'not', 'operand' => ' != '],
226
            'wildcard'  => ['method' => 'like', 'operand' => ' LIKE '],
227
            'prefix'    => ['method' => 'like', 'operand' => ' LIKE '],
228
        ];
229
        if (strpos($key, '__') !== false) {
230
            preg_match('/__(.*?)$/', $key, $matches);
231
            $key        = str_replace($matches[0], '', $key);
232
            $queryOperator   = $matches[1];
233
            $method     = $options[$queryOperator]['method'];
234
            $operator   = $options[$queryOperator]['operand'];
235
            switch ($queryOperator) {
236
                case 'wildcard':
237
                    $value = '%'.str_replace(array('?', '*'), array('_', '%'), $value).'%';
238
                    break;
239
                case 'prefix':
240
                    $value .= '%';
241
                    break;
242
            }
243
        }
244
        return [
245
            'key'       => $key,
246
            'operand'   => $operator,
247
            'method'    => $method,
248
            'value'     => $value
249
        ];
250
    }
251
}
252