Completed
Push — master ( a17f1e...16125b )
by Mehmet
02:48
created

SQL   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 220
Duplicated Lines 10 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 61.43%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 40
c 2
b 1
f 0
lcom 1
cbo 4
dl 22
loc 220
ccs 94
cts 153
cp 0.6143
rs 8.2608

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A connect() 0 13 1
A create() 0 3 1
A drop() 0 4 1
A truncate() 0 3 1
A createIndexes() 0 3 1
A insert() 0 8 2
A update() 0 4 1
A delete() 0 8 2
A get() 0 4 1
C find() 22 75 16
A query() 0 4 1
C buildFilter() 0 58 11

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 SQL 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 SQL, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Soupmix;
4
/*
5
SQL Adapter
6
*/
7
8
use Doctrine\DBAL\DriverManager;
9
10
class SQL implements Base
11
{
12
    public $conn = null;
13
    private $defaults = [
14
        'db_name'   => 'default',
15
        'user_name' => '',
16
        'password'  => '',
17
        'host'      => '127.0.0.1',
18
        'port'      => 3306,
19
        'charset'   => 'utf8',
20
        'driver'    => 'pdo_mysql',
21
    ];
22
23 2
    public function __construct($config)
24
    {
25 2
        $config = array_merge($this->defaults, $config);
26 2
        $this->connect($config);
27 2
    }
28
29 2
    public function connect($config)
30
    {
31
        $connectionParams = array(
32 2
            'dbname' => $config['db_name'],
33 2
            'user' => $config['user_name'],
34 2
            'password' => $config['password'],
35 2
            'host' => $config['host'],
36 2
            'port' => $config['port'],
37 2
            'charset' => $config['charset'],
38 2
            'driver' => $config['driver'],
39 2
        );
40 2
        $this->conn = DriverManager::getConnection($connectionParams);
41 2
    }
42
43
    public function create($collection)
44
    {
45
    }
46
47
    public function drop($collection)
48
    {
49
50
    }
51
52
    public function truncate($collection)
53
    {
54
    }
55
56
    public function createIndexes($collection, $indexes)
57
    {
58
    }
59
60 2
    public function insert($collection, $values)
61
    {
62 2
        $insertion = $this->conn->insert($collection, $values);
63 2
        if($insertion !== 0) {
64 2
            return $this->conn->lastInsertId();
65
        }
66
        return null;
67
    }
68
69
    public function update($collection, $filter, $values)
70
    {
71
        return $this->conn->update($collection, $values, $filter);
72
    }
73
74 2
    public function delete($collection, $filter)
75
    {
76 2
        $numberOfDeletedItems = $this->conn->delete($collection, $filter);
77 2
        if ($numberOfDeletedItems>0) {
78 2
            return 1;
79
        }
80
        return 0;
81
    }
82
83 1
    public function get($collection, $docId)
84
    {
85 1
        return $this->conn->fetchAssoc('SELECT * FROM '.$collection.' WHERE id = ?', array($docId));
86
    }
87
88 2
    public function find($collection, $filters, $fields = null, $sort = null, $start = 0, $limit = 25, $debug = false)
89
    {
90 1
        $result = null;
91 1
        $queryBuilder = $this->conn->createQueryBuilder();
92 1
        $queryBuilder->from($collection);
93 1
        if ($filters !== null) {
94 1
            foreach ($filters as $key => $value) {
95 1
                if (strpos($key, '__')!==false) {
96 1
                    $sqlOptions = self::buildFilter([$key=>$value]);
97
98 1 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...
99
                        $queryBuilder->andWhere(
100
                            $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
101
                        );
102
                    }
103
                    else{
104 1
                        $queryBuilder->andWhere(
105 1
                            $sqlOptions['key']
106 1
                            . ' ' . $sqlOptions['operand']
107 1
                            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']));
108
                    }
109
110
111 1
                } elseif (strpos($key, '__') === false && is_array($value)) {
112 1
                    foreach ($value as $orValue) {
113 1
                        $subKey = array_keys($orValue)[0];
114 1
                        $subValue = $orValue[$subKey];
115 1
                        if (strpos($subKey, '__')!==false) {
116 1
                            $sqlOptions = self::buildFilter([$subKey=>$subValue]);
117
118 1 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...
119
                                $queryBuilder->orWhere(
120
                                    $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
121
                                );
122
                            }
123
                            else{
124 1
                                $queryBuilder->orWhere(
125 1
                                    $sqlOptions['key']
126 1
                                    . ' ' . $sqlOptions['operand']
127 1
                                    . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']));
128
                            }
129 1
                        } else {
130
                            $queryBuilder->orWhere($subKey . '=' . $queryBuilder->createNamedParameter($subValue));
131
                        }
132 1
                    }
133 1
                } else {
134 1
                    $queryBuilder->andWhere($key . "=" . $queryBuilder->createNamedParameter($value));
135
                }
136 1
            }
137 1
        }
138 2
        if ($sort !== null) {
139
            $params['sort'] = '';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

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:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

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 the bar 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.

Loading history...
140
            foreach ($sort as $sort_key => $sort_dir) {
141 1
                if ($params['sort']!='') {
142
                    $params['sort'] .= ',';
143
                }
144
                $queryBuilder->addOrderBy($sort_key, $sort_dir);
145
            }
146
        }
147 1
        $queryBuilderForResult = clone $queryBuilder;
148 1
        $queryBuilder->select(" COUNT(*) AS total ");
149 1
        $stmt = $this->conn->executeQuery($queryBuilder->getSql(), $queryBuilder->getParameters());
150 1
        $count = $stmt->fetchAll(\PDO::FETCH_ASSOC);
151 1
        $numberOfSet = 0;
152 1
        if (isset($count[0]['total']) && ($count[0]['total']>0)) {
153 1
            $numberOfSet = $count[0]['total'];
154 1
            $fields = ($fields === null) ? "*" : $fields;
155 1
            $queryBuilderForResult->select($fields)
156 1
                ->setFirstResult($start)
157 1
                ->setMaxResults($limit);
158 1
            $stmt = $this->conn->executeQuery($queryBuilderForResult->getSql(), $queryBuilderForResult->getParameters());
159 1
            $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
160 1
        }
161 2
        return ['total' => $numberOfSet, 'data' => $result];
162
    }
163
164
    public function query($query)
165
    {
166
        // reserved
167
    }
168
169 2
    public static function buildFilter($filter)
170
    {
171 1
        $key = array_keys($filter)[0];
172 2
        $value = $filter[$key];
173 1
        $operator = ' = ';
174 1
        $method = 'eq';
175 1
        if (strpos($key, '__')!==false) {
176 1
            preg_match('/__(.*?)$/i', $key, $matches);
177 1
            $operator = $matches[1];
178
            switch ($operator) {
179 1
                case 'gte':
180 1
                    $operator = ' >= ';
181 1
                    $method = 'gte';
182 1
                    break;
183 1
                case 'gt':
184
                    $operator = ' > ';
185
                    $method = 'gt';
186
                    break;
187 1
                case 'lte':
188 1
                    $operator = ' <= ';
189 1
                    $method = 'lte';
190 1
                    break;
191
                case 'lt':
192
                    $operator = ' < ';
193
                    $method = 'lt';
194
                    break;
195
                case 'in':
196
                    $operator = ' IN ';
197
                    $method = 'in';
198
                    break;
199
                case 'nin':
200
                    $operator = ' NOT IN ';
201
                    $method = 'notIn';
202
                    break;
203
                case 'not':
204
                    $operator = ' != ';
205
                    $method = 'not';
206
                    break;
207
                case 'wildcard':
208
                    $operator = ' LIKE ';
209
                    $method = 'like';
210
                    $value = str_replace(array('?','*'), array('_','%'), $value);
211
                    break;
212
                case 'prefix':
213
                    $operator = ' LIKE ';
214
                    $method = 'like';
215
                    $value = $value.'%';
216
                    break;
217
            }
218 1
        }
219
        return [
220 1
            'key'       => str_replace($matches[0], '', $key),
0 ignored issues
show
Bug introduced by
The variable $matches does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
221 1
            'operand'   => $operator,
222 1
            'method'    => $method,
223
            'value'     => $value
224 1
        ];
225
226
    }
227
228
229
}
230