Completed
Push — master ( 8968b1...9cd635 )
by Mehmet
02:51
created

SQL   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 262
Duplicated Lines 16.03 %

Coupling/Cohesion

Components 2
Dependencies 9

Test Coverage

Coverage 74.59%

Importance

Changes 8
Bugs 1 Features 1
Metric Value
wmc 43
c 8
b 1
f 1
lcom 2
cbo 9
dl 42
loc 262
ccs 138
cts 185
cp 0.7459
rs 8.3157

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getConnection() 0 4 1
C create() 10 32 7
A drop() 0 9 2
A truncate() 0 4 1
B createIndexes() 10 24 6
A insert() 0 8 2
A update() 0 4 1
A delete() 0 8 2
A get() 0 4 1
C find() 22 65 14
A query() 0 4 1
B buildFilter() 0 53 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 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\Connection;
9
use Doctrine\DBAL\Schema\Table;
10
use Doctrine\DBAL\Schema\Column;
11
use Doctrine\DBAL\Types\Type;
12
use Doctrine\DBAL\Schema\Index;
13
14
class SQL implements Base
0 ignored issues
show
Bug introduced by
There is one abstract method connect in this class; you could implement it, or declare this class as abstract.
Loading history...
15
{
16
    public $conn = null;
17
    private $defaults = [
18
        'db_name'   => 'default',
19
        'user_name' => '',
20
        'password'  => '',
21
        'host'      => '127.0.0.1',
22
        'port'      => 3306,
23
        'charset'   => 'utf8',
24
        'driver'    => 'pdo_mysql',
25
    ];
26
    private static $columnDefaults = [
27
        'name'      => null,
28
        'type'      => 'string',
29
        'type_info' => null,
30
        'maxLength' => 255,
31
        'default'   => null,
32
        'index'     => null,
33
        'index_type'=> null,
34
]   ;
35
36 2
    public function __construct($config, Connection $client)
37
    {
38 2
        $config = array_merge($this->defaults, $config);
0 ignored issues
show
Unused Code introduced by
$config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
39 2
        $this->conn = $client;
40 2
41
    }
42 2
43
    public function getConnection()
44
    {
45 2
        return $this->conn;
46 2
    }
47 2
48 2
    public function create($collection, $fields)
49 2
    {
50 2
        $columns = [];
51 2
        $indexes = [];
52 2
        $schemaManager = $this->conn->getSchemaManager();
53 2
        $columns[] = new Column('id', Type::getType('integer'), ['unsigned' => true, 'autoincrement' => true] );
54 2
        $indexes[] = new Index($collection.'_PK', ['id'], false, true);
55
        $tmpIndexes = [];
56 2
        foreach ($fields as $field){
57
            $field = array_merge(self::$columnDefaults, $field);
58 2
            $options = [];
59 2
            if ($field['type'] == 'integer' && $field['type_info'] == 'unsigned') {
60 2
                $options['unsigned'] = true;
61 2
            }
62 2
            $options['length'] = $field['maxLength'];
63 2
            $options['default'] = $field['default'];
64 2 View Code Duplication
            if ($field['index'] !== null) {
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...
65 2
                if ( $field['index_type'] == 'unique' ) {
66 2
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
67 2
                } else {
68
                    $tmpIndexes[] = $field['name'];
69
                }
70 2
            }
71 2
72 2
            $columns[] = new Column($field['name'], Type::getType($field['type']), $options );
73 2
        }
74 2 View Code Duplication
        if(count($tmpIndexes)>0){
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...
75 2
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
76 2
        }
77
        $table = new Table($collection, $columns, $indexes);
78 2
        return $schemaManager->createTable($table);
79
    }
80 2
81 2
    public function drop($collection)
82 2
    {
83 2
        $schemaManager = $this->conn->getSchemaManager();
84 2
        if ($schemaManager->tablesExist([$collection])) {
85 2
            return $schemaManager->dropTable($collection);
86 2
        } else {
87
            return null;
88
        }
89 2
    }
90
91 2
    public function truncate($collection)
92 2
    {
93 1
        return $this->client->conn->query('TRUNCATE TABLE `' . $collection . '`');
0 ignored issues
show
Bug introduced by
The property client does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
94
    }
95 1
96
    public function createIndexes($collection, $indexes)
97
    {
98
        $schemaManager = $this->conn->getSchemaManager();
99
100
        $tmpIndexes = [];
101
        foreach ($indexes as $field){
102
            $field = array_merge(self::$columnDefaults, $field);
103 View Code Duplication
            if ($field['index'] !== null) {
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...
104
                if ( $field['index_type'] == 'unique' ) {
105
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
106
                } else {
107
                    $tmpIndexes[] = $field['name'];
108
                }
109
            }
110
        }
111 View Code Duplication
        if (count($tmpIndexes) > 0) {
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...
112
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
113
        }
114
        foreach ($indexes as $index) {
115
            $schemaManager->createIndex($index, $collection);
116
        }
117
118
119
    }
120
121
    public function insert($collection, $values)
122
    {
123
        $insertion = $this->conn->insert($collection, $values);
124
        if($insertion !== 0) {
125
            return $this->conn->lastInsertId();
126
        }
127
        return null;
128
    }
129 2
130
    public function update($collection, $filter, $values)
131 2
    {
132 2
        return $this->conn->update($collection, $values, $filter);
133 2
    }
134
135
    public function delete($collection, $filter)
136
    {
137
        $numberOfDeletedItems = $this->conn->delete($collection, $filter);
138 1
        if ($numberOfDeletedItems>0) {
139
            return 1;
140
        }
141 1
        return 0;
142
    }
143 2
144
    public function get($collection, $docId)
145 2
    {
146 2
        return $this->conn->fetchAssoc('SELECT * FROM '.$collection.' WHERE id = ?', array($docId));
147 2
    }
148
149
    public function find($collection, $filters, $fields = null, $sort = null, $start = 0, $limit = 25, $debug = false)
150
    {
151
        $result = null;
152 1
        $queryBuilder = $this->conn->createQueryBuilder();
153
        $queryBuilder->from($collection);
154 1
        if ($filters !== null) {
155
            foreach ($filters as $key => $value) {
156
                 if (strpos($key, '__') === false && is_array($value)) {
157 2
                    foreach ($value as $orValue) {
158
                        $subKey = array_keys($orValue)[0];
159 1
                        $subValue = $orValue[$subKey];
160 1
                        $sqlOptions = self::buildFilter([$subKey=>$subValue]);
161 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...
162 1
                            $queryBuilder->orWhere(
163 1
                                $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
164 1
                            );
165 1
                        }
166 1
                        else{
167 1
                            $queryBuilder->orWhere(
168 1
                                $sqlOptions['key']
169 1
                                . ' ' . $sqlOptions['operand']
170
                                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']));
171
                        }
172 1
                    }
173
                } else {
174 1
                    $sqlOptions = self::buildFilter([$key=>$value]);
175 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...
176 1
                        $queryBuilder->andWhere(
177 1
                            $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
178 1
                        );
179
                    }
180 1
                    else{
181 1
                        $queryBuilder->andWhere(
182 1
                            $sqlOptions['key']
183 1
                            . ' ' . $sqlOptions['operand']
184
                            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']));
185
                    }
186
                }
187
            }
188
        }
189 1
        if ($sort !== null) {
190 1
            $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...
191 1
            foreach ($sort as $sort_key => $sort_dir) {
192 1
                if ($params['sort']!='') {
193
                    $params['sort'] .= ',';
194
                }
195 1
                $queryBuilder->addOrderBy($sort_key, $sort_dir);
196 1
            }
197 1
        }
198
        $queryBuilderCount = clone $queryBuilder;
199
        $queryBuilderCount->select(" COUNT(*) AS total ");
200
        $stmt = $this->conn->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters());
201
        $count = $stmt->fetchAll(\PDO::FETCH_ASSOC);
202
        $numberOfSet = 0;
203
        if (isset($count[0]['total']) && ($count[0]['total']>0)) {
204
            $numberOfSet = $count[0]['total'];
205
            $fields = ($fields === null) ? "*" : $fields;
206 1
            $queryBuilder->select($fields)
207 1
                ->setFirstResult($start)
208 1
                ->setMaxResults($limit);
209 1
            $stmt = $this->conn->executeQuery($queryBuilder->getSql(), $queryBuilder->getParameters());
210 1
            $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
211 1
        }
212 1
        return ['total' => $numberOfSet, 'data' => $result];
213 1
    }
214 1
215 1
    public function query($collection)
216 1
    {
217 1
        return new SQLQueryBuilder($collection);
218 1
    }
219 1
220 1
    public static function buildFilter($filter)
221
    {
222
        $key = array_keys($filter)[0];
223
        $value = $filter[$key];
224
        $operator = ' = ';
225
        $method = 'eq';
226
227
        $methods = [
228 1
            'gte'   => 'gte',
229
            'gt'    => 'gt',
230 1
            'lte'   => 'lte',
231 1
            'lt'    => 'lt',
232 1
            'in'    => 'in',
233 1
            '!in'   => 'notIn',
234
            'not'   => 'not',
235
            'wildchard' => 'like',
236 1
            'prefix' => 'like',
237 1
        ];
238 1
        $operands = [
239 1
            'gte'   => ' >= ',
240 1
            'gt'    => ' > ',
241 1
            'lte'   => ' <= ',
242 1
            'lt'    => ' < ',
243 1
            'in'    => ' IN ',
244 1
            '!in'   => ' NOT IN',
245 1
            'not'   => ' NOT',
246
            'wildchard' => ' LIKE ',
247 1
            'prefix' => ' LIKE ',
248 1
        ];
249 1
250 1
        if (strpos($key, '__')!==false) {
251 1
            preg_match('/__(.*?)$/i', $key, $matches);
252 1
            $key        = str_replace($matches[0], '', $key);
253 1
            $operator   = $matches[1];
254 1
            $method     = $methods[$operator];
255 1
            $operator   = $operands[$operator];
256 1
            switch ($operator) {
257
                case 'wildcard':
258 1
                    $value = str_replace(array('?', '*'), array('_', '%'), $value);
259 1
                    break;
260 1
                case 'prefix':
261 1
                    $value = $value.'%';
262 1
                    break;
263 1
            }
264
        }
265 1
        return [
266
            'key'       => $key,
267
            'operand'   => $operator,
268 1
            'method'    => $method,
269
            'value'     => $value
270
        ];
271
272 1
    }
273
274 1
275
}
276