Completed
Push — master ( 27e459...e85500 )
by Mehmet
02:15
created

SQL   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 239
Duplicated Lines 12.55 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 81.71%

Importance

Changes 15
Bugs 4 Features 1
Metric Value
wmc 42
c 15
b 4
f 1
lcom 2
cbo 8
dl 30
loc 239
ccs 134
cts 164
cp 0.8171
rs 8.295

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getConnection() 0 4 1
C create() 10 31 7
A drop() 0 9 2
A truncate() 0 4 1
B createIndexes() 10 21 6
A insert() 0 8 2
A update() 0 4 1
A delete() 0 8 2
A get() 0 4 1
A find() 0 16 3
B buildQuery() 0 15 5
A buildQueryForAnd() 6 16 2
A buildQueryForOr() 4 22 3
A query() 0 4 1
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 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
15
{
16
    protected $doctrine = null;
17
    protected $dbName = null;
18
    protected static $columnDefaults = [
19
        'name'      => null,
20
        'type'      => 'string',
21
        'type_info' => null,
22
        'maxLength' => 255,
23
        'default'   => null,
24
        'index'     => null,
25
        'index_type'=> null,
26
]   ;
27
28 3
    public function __construct($config, Connection $client)
29
    {
30 3
        $this->doctrine = $client;
31 3
        $this->dbName = $config['db_name'];
32 3
    }
33
34 2
    public function getConnection()
35
    {
36 2
        return $this->doctrine;
37
    }
38
39 3
    public function create($collection, $fields)
40
    {
41 3
        $columns = [];
42 3
        $indexes = [];
43 3
        $schemaManager = $this->doctrine->getSchemaManager();
44 3
        $columns[] = new Column('id', Type::getType('integer'), ['unsigned' => true, 'autoincrement' => true] );
45 3
        $indexes[] = new Index($collection.'_PK', ['id'], false, true);
46 3
        $tmpIndexes = [];
47 3
        foreach ($fields as $field){
48 3
            $field = array_merge(self::$columnDefaults, $field);
49 3
            $options = [];
50 3
            if ($field['type'] == 'integer' && $field['type_info'] == 'unsigned') {
51
                $options['unsigned'] = true;
52
            }
53 3
            $options['length'] = $field['maxLength'];
54 3
            $options['default'] = $field['default'];
55 3 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...
56 3
                if ( $field['index_type'] == 'unique' ) {
57 3
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
58 3
                } else {
59 3
                    $tmpIndexes[] = $field['name'];
60
                }
61 3
            }
62 3
            $columns[] = new Column($field['name'], Type::getType($field['type']), $options );
63 3
        }
64 3 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...
65 3
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
66 3
        }
67 3
        $table = new Table($collection, $columns, $indexes);
68 3
        return $schemaManager->createTable($table);
69
    }
70
71 3
    public function drop($collection)
72
    {
73 3
        $schemaManager = $this->doctrine->getSchemaManager();
74 3
        if ($schemaManager->tablesExist([$collection])) {
75 2
            return $schemaManager->dropTable($collection);
76
        } else {
77 1
            return null;
78
        }
79
    }
80
81
    public function truncate($collection)
82
    {
83
        return $this->client->doctrine->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...
84
    }
85
86
    public function createIndexes($collection, $indexes)
87
    {
88
        $schemaManager = $this->doctrine->getSchemaManager();
89
        $tmpIndexes = [];
90
        foreach ($indexes as $field){
91
            $field = array_merge(self::$columnDefaults, $field);
92 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...
93
                if ( $field['index_type'] == 'unique' ) {
94
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
95
                } else {
96
                    $tmpIndexes[] = $field['name'];
97
                }
98
            }
99
        }
100 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...
101
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
102
        }
103
        foreach ($indexes as $index) {
104
            $schemaManager->createIndex($index, $collection);
105
        }
106
    }
107
108 3
    public function insert($collection, $values)
109
    {
110 3
        $insertion = $this->doctrine->insert($collection, $values);
111 3
        if($insertion !== 0) {
112 3
            return $this->doctrine->lastInsertId();
113
        }
114
        return null;
115
    }
116
117
    public function update($collection, $filter, $values)
118
    {
119
        return $this->doctrine->update($collection, $values, $filter);
120
    }
121
122 2
    public function delete($collection, $filter)
123
    {
124 2
        $numberOfDeletedItems = $this->doctrine->delete($collection, $filter);
125 2
        if ($numberOfDeletedItems>0) {
126 2
            return 1;
127
        }
128
        return 0;
129
    }
130
131 1
    public function get($collection, $docId)
132
    {
133 1
        return $this->doctrine->fetchAssoc('SELECT * FROM ' . $collection . ' WHERE id = ?', array($docId));
134
    }
135
136 1
    public function find($collection, $filters, $fields = null, $sort = null, $offset = 0, $limit = 25, $debug = false)
137
    {
138 1
        $query = $this->query($collection);
139 1
        foreach ($filters as $filter => $value) {
140 1
            if (is_array($value)) {
141 1
                $query->orFilters($value);
142 1
            } else {
143 1
                $query->andFilter($filter, $value);
144
            }
145 1
        }
146 1
        return $query->returnFields($fields)
147 1
            ->sortFields($sort)
148 1
            ->offset($offset)
149 1
            ->limit($limit)
150 1
            ->run();
151
    }
152
153 2
    public function buildQuery($collection, $filters)
154
    {
155 2
        $queryBuilder = $this->doctrine->createQueryBuilder();
156 2
        $queryBuilder->from($collection);
157 2
        if ($filters !== null) {
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
        }
166 2
        return $queryBuilder;
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']}( $sqlOptions['key'], $sqlOptions['value'])
174 1
            );
175
            return $queryBuilder;
176
        }
177 2
        $queryBuilder->andWhere(
178 2
                '`'.$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']}( $sqlOptions['key'], $sqlOptions['value']);
193 1
                continue;
194
            }
195 2
            $orQuery[] =
196 2
                '`'.$sqlOptions['key'].'`'
197 2
                . ' ' . $sqlOptions['operand']
198 2
                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
199
200 2
        }
201 2
        $queryBuilder->andWhere(
202 2
            '(' . implode(' OR ', $orQuery) . ')'
203 2
        );
204 2
        return $queryBuilder;
205
    }
206
207 2
    public function query($collection)
208
    {
209 2
        return new SQLQueryBuilder($collection, $this);
210
    }
211
212 2
    public static function buildFilter($filter)
213
    {
214 2
        $key = array_keys($filter)[0];
215 2
        $value = $filter[$key];
216 2
        $operator = ' = ';
217 2
        $method = 'eq';
218
        $options =[
219 2
            'gte'       => ['method' => 'gte', 'operand' => ' >= '],
220 2
            'gt'        => ['method' => 'gt', 'operand' => ' > '],
221 2
            'lte'       => ['method' => 'lte', 'operand' => ' <= '],
222 2
            'lt'        => ['method' => 'lt', 'operand' => ' < '],
223 2
            'in'        => ['method' => 'in', 'operand' => ' IN '],
224 2
            '!in'       => ['method' => 'notIn', 'operand' => ' NOT IN '],
225 2
            'not'       => ['method' => 'not', 'operand' => ' NOT '],
226 2
            'wildcard'  => ['method' => 'like', 'operand' => ' LIKE '],
227 2
            'prefix'    => ['method' => 'like', 'operand' => ' LIKE '],
228 2
        ];
229 2
        if (strpos($key, '__') !== false) {
230 2
            preg_match('/__(.*?)$/i', $key, $matches);
231 2
            $key        = str_replace($matches[0], '', $key);
232 2
            $queryOperator   = $matches[1];
233 2
            $method     = $options[$queryOperator]['method'];
234 2
            $operator   = $options[$queryOperator]['operand'];
235
            switch ($queryOperator) {
236 2
                case 'wildcard':
237 1
                    $value = '%'.str_replace(array('?', '*'), array('_', '%'), $value).'%';
238 1
                    break;
239 2
                case 'prefix':
240 1
                    $value = $value.'%';
241 1
                    break;
242
            }
243 2
        }
244
        return [
245 2
            'key'       => $key,
246 2
            'operand'   => $operator,
247 2
            'method'    => $method,
248
            'value'     => $value
249 2
        ];
250
    }
251
252
}
253