Completed
Push — master ( acf587...06b199 )
by Mehmet
02:23
created

SQLQueryBuilder   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 242
Duplicated Lines 4.13 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 92.22%

Importance

Changes 13
Bugs 5 Features 2
Metric Value
wmc 47
c 13
b 5
f 2
lcom 1
cbo 1
dl 10
loc 242
ccs 166
cts 180
cp 0.9222
rs 8.439

15 Methods

Rating   Name   Duplication   Size   Complexity  
A getQueryBuilder() 0 8 2
A getCount() 0 7 1
A setSortOrders() 0 8 3
A run() 0 21 4
A setJoins() 0 7 1
B setJoinsForType() 0 26 6
A returnFieldsForJoin() 0 8 3
A setReturnFields() 0 9 3
A setOffsetAndLimit() 0 5 1
C addAlias() 0 27 8
A buildQuery() 0 9 2
A buildQueryFilters() 0 11 4
A buildQueryForAnd() 6 16 2
A buildQueryForOr() 4 21 3
B buildFilter() 0 39 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SQLQueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SQLQueryBuilder, and based on these observations, apply Extract Interface, too.

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
        $this->setJoins();
14 2
        $count = $this->getCount();
15 2
        if (!isset($count[0]['total']) || ($count[0]['total']==0)) {
16
            return ['total' => 0, 'data' => null];
17
        }
18 2
        $numberOfRows = $count[0]['total'];
19 2
        $this->setSortOrders();
20 2
        $this->setOffsetAndLimit();
21 2
        $this->setReturnFields();
22 2
        $stmt = $this->conn->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
        return ['total' => $numberOfRows, 'data' => $result];
31
    }
32
33 2
    private function getQueryBuilder()
34
    {
35 2
        if ($this->orFilters !== null) {
36 2
            $this->andFilters[] = $this->orFilters;
37 2
        }
38 2
        $this->filters      = $this->andFilters;
39 2
        return $this->buildQuery($this->collection, $this->filters);
40
    }
41
42 2
    private function getCount()
43
    {
44 2
        $queryBuilderCount = clone $this->queryBuilder;
45 2
        $queryBuilderCount->select(" COUNT(*) AS total ");
46 2
        $stmt = $this->conn->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters());
47 2
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
48
    }
49
50 2
    private function setSortOrders()
51
    {
52 2
        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 2
    }
58
59 2
    private function setJoins()
60
    {
61 2
        $this->setJoinsForType('innerJoin');
62 2
        $this->setJoinsForType('leftJoin');
63 2
        $this->setJoinsForType('rightJoin');
64 2
        $this->setJoinsForType('outerJoin');
65 2
    }
66
67 2
    private function setJoinsForType($joinType)
68
    {
69 2
        if (is_null($this->{$joinType})) {
70 2
           return;
71
        }
72 1
        foreach ($this->{$joinType} as $collectionName => $collection) {
73 1
            $fieldNames = $this->addAlias($collection['returnFields'], $collectionName);
74 1
            $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 1
            $joinCondition = '';
76 1
            foreach ($collection['relations'] as $relation) {
77 1
                $joinCondition .= ($joinCondition=='') ? '':' AND ';
78 1
                $relationType = array_keys($relation)[0];
79 1
                $source = array_keys($relation[$relationType])[0];
80 1
                $condition = $collectionName . "." . $source
81 1
                    . " = " . $this->collection . "." . $relation[$relationType][$source];
82 1
                if($relationType != 'field') {
83 1
                    $condition = $collectionName . "." . $source . " "
84 1
                        . $relationType . " " . $relation[$relationType][$source];
85 1
                }
86 1
                $joinCondition .= $condition;
87 1
            }
88 1
            $this->queryBuilder->$joinType($this->collection, $collectionName, $collectionName, $joinCondition);
89
90 1
        }
91 1
        return $this;
92
    }
93 1
    public function returnFieldsForJoin(array $fieldNames=null)
94
    {
95 1
        if($fieldNames !== null ) {
96 1
            foreach ($fieldNames as $fieldName) {
97 1
                $this->fieldNames[] = $fieldName;
98 1
            }
99 1
        }
100 1
    }
101
102 2
    private function setReturnFields()
103
    {
104 2
        if ($this->distinctFieldName === null) {
105 2
            $fieldNames = ($this->fieldNames === null) ? $this->addAlias("*") : $this->addAlias($this->fieldNames);
106 2
            $this->queryBuilder->select($fieldNames);
107 2
            return;
108
        }
109 1
        $this->queryBuilder->select('DISTINCT (`' . $this->collection . "`.`" . $this->distinctFieldName . '`)');
110 1
    }
111
112 2
    private function setOffsetAndLimit()
113
    {
114 2
        $this->queryBuilder->setFirstResult($this->offset)
115 2
            ->setMaxResults($this->limit);
116 2
    }
117
118 2
    private function addAlias($fields, $collection=null)
119
    {
120 2
        $collection = (!is_null($collection)) ? $collection : $this->collection;
121 2
        if (!is_array($fields)) {
122 1
            return  $collection . "." . $fields;
123
        }
124 1
        if (!is_array($fields)) {
125
           return  $collection . "." . $fields;
126
        }
127 1
        $newFields = [];
128 1
        foreach ($fields as $field => $value) {
129 1
            if (strpos($value, ".")!== false) {
130 1
                $newFields[] = $value;
131 1
                continue;
132
            }
133 1
            if (is_int($field)) {
134 1
                if (!is_array($fields)) {
135
                    $newFields[] = $collection . "." . $fields;
136
                    continue;
137
                }
138 1
                $newFields[] = $collection . "." . $value;
139 1
                continue;
140
            }
141
            $newFields[$collection.".".$field] = $value;
142 1
        }
143 1
        return $newFields;
144
    }
145
146 2
    protected function buildQuery($collection, $filters)
147
    {
148 2
        $queryBuilder = $this->conn->createQueryBuilder();
149 2
        $queryBuilder->from($collection, $collection);
150 2
        if ($filters === null) {
151
            return $queryBuilder;
152
        }
153 2
        return $this->buildQueryFilters($queryBuilder, $filters);
154
    }
155
156 2
    protected function buildQueryFilters($queryBuilder, $filters)
157
    {
158 2
        foreach ($filters as $key => $value) {
159 2
            if (strpos($key, '__') === false && is_array($value)) {
160 2
                $queryBuilder = $this->buildQueryForOr($queryBuilder, $value);
161 2
                continue;
162
            }
163 2
            $queryBuilder = $this->buildQueryForAnd($queryBuilder, $key, $value);
164 2
        }
165 2
        return $queryBuilder;
166
    }
167
168 2
    protected function buildQueryForAnd($queryBuilder, $key, $value)
169
    {
170 2
        $sqlOptions = self::buildFilter([$key => $value]);
171 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...
172
            $queryBuilder->andWhere(
173
                $queryBuilder->expr()->{$sqlOptions['method']}($this->collection . "." . $sqlOptions['key'], $sqlOptions['value'])
174
            );
175
            return $queryBuilder;
176
        }
177 2
        $queryBuilder->andWhere(
178 2
            '`' . $this->collection . "`.`" . $sqlOptions['key'].'`'
179 2
            . ' ' . $sqlOptions['operand']
180 2
            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
181 2
        );
182 2
        return $queryBuilder;
183
    }
184 2
    protected function buildQueryForOr($queryBuilder, $value)
185
    {
186 2
        $orQuery =[];
187 2
        foreach ($value as $orValue) {
188 2
            $subKey = array_keys($orValue)[0];
189 2
            $subValue = $orValue[$subKey];
190 2
            $sqlOptions = self::buildFilter([$subKey => $subValue]);
191 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...
192 1
                $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}($this->collection . "." . $sqlOptions['key'], $sqlOptions['value']);
193 1
                continue;
194
            }
195 2
            $orQuery[] =
196 2
                '`' . $this->collection . "`.`" . $sqlOptions['key'].'`'
197 2
                . ' ' . $sqlOptions['operand']
198 2
                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
199 2
        }
200 2
        $queryBuilder->andWhere(
201 2
            '(' . implode(' OR ', $orQuery) . ')'
202 2
        );
203 2
        return $queryBuilder;
204
    }
205
206
207 2
    public static function buildFilter($filter)
208
    {
209 2
        $key = array_keys($filter)[0];
210 2
        $value = $filter[$key];
211 2
        $operator = ' = ';
212 2
        $method = 'eq';
213
        $options =[
214 2
            'gte'       => ['method' => 'gte', 'operand' => ' >= '],
215 2
            'gt'        => ['method' => 'gt', 'operand' => ' > '],
216 2
            'lte'       => ['method' => 'lte', 'operand' => ' <= '],
217 2
            'lt'        => ['method' => 'lt', 'operand' => ' < '],
218 2
            'in'        => ['method' => 'in', 'operand' => ' IN '],
219 2
            '!in'       => ['method' => 'notIn', 'operand' => ' NOT IN '],
220 2
            'not'       => ['method' => 'not', 'operand' => ' NOT '],
221 2
            'wildcard'  => ['method' => 'like', 'operand' => ' LIKE '],
222 2
            'prefix'    => ['method' => 'like', 'operand' => ' LIKE '],
223 2
        ];
224 2
        if (strpos($key, '__') !== false) {
225 2
            preg_match('/__(.*?)$/i', $key, $matches);
226 2
            $key        = str_replace($matches[0], '', $key);
227 2
            $queryOperator   = $matches[1];
228 2
            $method     = $options[$queryOperator]['method'];
229 2
            $operator   = $options[$queryOperator]['operand'];
230
            switch ($queryOperator) {
231 2
                case 'wildcard':
232 1
                    $value = '%'.str_replace(array('?', '*'), array('_', '%'), $value).'%';
233 1
                    break;
234 2
                case 'prefix':
235 1
                    $value = $value.'%';
236 1
                    break;
237
            }
238 2
        }
239
        return [
240 2
            'key'       => $key,
241 2
            'operand'   => $operator,
242 2
            'method'    => $method,
243
            'value'     => $value
244 2
        ];
245
    }
246
247
}