Completed
Push — master ( 9a7f03...117e39 )
by Mehmet
02:52
created

SQL::buildQuery()   C

Complexity

Conditions 8
Paths 2

Size

Total Lines 46
Code Lines 31

Duplication

Lines 13
Ratio 28.26 %

Code Coverage

Tests 26
CRAP Score 9.6817

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 13
loc 46
ccs 26
cts 37
cp 0.7027
rs 5.5555
cc 8
eloc 31
nc 2
nop 2
crap 9.6817
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 $conn = 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 2
    public function __construct($config, Connection $client)
29
    {
30 2
        $this->conn = $client;
31 2
        $this->dbName = $config['db_name'];
32 2
    }
33
34
    public function getConnection()
35
    {
36
        return $this->conn;
37
    }
38
39 2
    public function create($collection, $fields)
40
    {
41 2
        $columns = [];
42 2
        $indexes = [];
43 2
        $schemaManager = $this->conn->getSchemaManager();
44 2
        $columns[] = new Column('id', Type::getType('integer'), ['unsigned' => true, 'autoincrement' => true] );
45 2
        $indexes[] = new Index($collection.'_PK', ['id'], false, true);
46 2
        $tmpIndexes = [];
47 2
        foreach ($fields as $field){
48 2
            $field = array_merge(self::$columnDefaults, $field);
49 2
            $options = [];
50 2
            if ($field['type'] == 'integer' && $field['type_info'] == 'unsigned') {
51
                $options['unsigned'] = true;
52
            }
53 2
            $options['length'] = $field['maxLength'];
54 2
            $options['default'] = $field['default'];
55 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...
56 2
                if ( $field['index_type'] == 'unique' ) {
57 2
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
58 2
                } else {
59 2
                    $tmpIndexes[] = $field['name'];
60
                }
61 2
            }
62
63 2
            $columns[] = new Column($field['name'], Type::getType($field['type']), $options );
64 2
        }
65 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...
66 2
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
67 2
        }
68 2
        $table = new Table($collection, $columns, $indexes);
69 2
        return $schemaManager->createTable($table);
70
    }
71
72 2
    public function drop($collection)
73
    {
74 2
        $schemaManager = $this->conn->getSchemaManager();
75 2
        if ($schemaManager->tablesExist([$collection])) {
76 1
            return $schemaManager->dropTable($collection);
77
        } else {
78 1
            return null;
79
        }
80
    }
81
82
    public function truncate($collection)
83
    {
84
        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...
85
    }
86
87
    public function createIndexes($collection, $indexes)
88
    {
89
        $schemaManager = $this->conn->getSchemaManager();
90
91
        $tmpIndexes = [];
92
        foreach ($indexes as $field){
93
            $field = array_merge(self::$columnDefaults, $field);
94 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...
95
                if ( $field['index_type'] == 'unique' ) {
96
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
97
                } else {
98
                    $tmpIndexes[] = $field['name'];
99
                }
100
            }
101
        }
102 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...
103
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
104
        }
105
        foreach ($indexes as $index) {
106
            $schemaManager->createIndex($index, $collection);
107
        }
108
109
110
    }
111
112 2
    public function insert($collection, $values)
113
    {
114 2
        $insertion = $this->conn->insert($collection, $values);
115 2
        if($insertion !== 0) {
116 2
            return $this->conn->lastInsertId();
117
        }
118
        return null;
119
    }
120
121
    public function update($collection, $filter, $values)
122
    {
123
        return $this->conn->update($collection, $values, $filter);
124
    }
125
126 2
    public function delete($collection, $filter)
127
    {
128 2
        $numberOfDeletedItems = $this->conn->delete($collection, $filter);
129 2
        if ($numberOfDeletedItems>0) {
130 2
            return 1;
131
        }
132
        return 0;
133
    }
134
135 1
    public function get($collection, $docId)
136
    {
137 1
        return $this->conn->fetchAssoc('SELECT * FROM '.$collection.' WHERE id = ?', array($docId));
138
    }
139
140 2
    public function find($collection, $filters, $fields = null, $sort = null, $start = 0, $limit = 25, $debug = false)
141
    {
142 1
        $result = null;
143 1
        $queryBuilder = $this->buildQuery($collection, $filters);
144 1
        $queryBuilderCount = clone $queryBuilder;
145 1
        $queryBuilderCount->select(" COUNT(*) AS total ");
146 1
        $stmt = $this->conn->executeQuery($queryBuilderCount->getSql(), $queryBuilderCount->getParameters());
147 1
        $count = $stmt->fetchAll(\PDO::FETCH_ASSOC);
148 1
        $numberOfSet = 0;
149 1
        if (isset($count[0]['total']) && ($count[0]['total']>0)) {
150 1
            $numberOfSet = $count[0]['total'];
151 1
            $fields = ($fields === null) ? "*" : $fields;
152 1
            if ($sort !== null) {
153
                $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...
154 View Code Duplication
                foreach ($sort as $sort_key => $sort_dir) {
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...
155
                    if ($params['sort']!='') {
156
                        $params['sort'] .= ',';
157
                    }
158 1
                    $queryBuilder->addOrderBy($sort_key, $sort_dir);
159 1
                }
160 1
            }
161 1
            $queryBuilder->select($fields)
162
                ->setFirstResult($start)
163 1
                ->setMaxResults($limit);
164 1
            $stmt = $this->conn->executeQuery($queryBuilder->getSql(), $queryBuilder->getParameters());
165 1
            $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
166 1
        }
167
        return ['total' => $numberOfSet, 'data' => $result];
168
    }
169
170
    public function buildQuery($collection, $filters)
171
    {
172 1
        $queryBuilder = $this->conn->createQueryBuilder();
173 1
        $queryBuilder->from($collection);
174 2
        if ($filters !== null) {
175 1
            foreach ($filters as $key => $value) {
176
                if (strpos($key, '__') === false && is_array($value)) {
177
                    $orQuery =[];
178 1
                    foreach ($value as $orValue) {
179 1
                        $subKey = array_keys($orValue)[0];
180 1
                        $subValue = $orValue[$subKey];
181
                        $sqlOptions = self::buildFilter([$subKey => $subValue]);
182
                        if(in_array($sqlOptions['method'], ['in', 'notIn'])){
183
                            $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value']);
184
                        }
185 View Code Duplication
                        else{
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...
186
                            $orQuery[] =
187
                                '`'.$sqlOptions['key'].'`'
188
                                . ' ' . $sqlOptions['operand']
189 1
                                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
190 1
                        }
191 1
                    }
192 1
193 1
                    $queryBuilder->andWhere(
194 1
                        implode(' OR ', $orQuery)
195 1
                    );
196 1
                } else {
197 1
                    $sqlOptions = self::buildFilter([$key=>$value]);
198 1
                    if(in_array($sqlOptions['method'], ['in', 'notIn', ''])){
199 1
                        $queryBuilder->andWhere(
200 1
                            $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
201 1
                        );
202 1
                    }
203 1 View Code Duplication
                    else{
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...
204
                        $queryBuilder->andWhere(
205
                            '`'.$sqlOptions['key'].'`'
206
                            . ' ' . $sqlOptions['operand']
207
                            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
208
                        );
209
                    }
210
                }
211 1
            }
212
        }
213 1
214 1
        return $queryBuilder;
215 1
    }
216 1
217
218
219 1
    public function query($collection)
220 1
    {
221 1
        return new SQLQueryBuilder($collection, $this);
0 ignored issues
show
Unused Code introduced by
The call to SQLQueryBuilder::__construct() has too many arguments starting with $this.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
222 1
    }
223 1
224 1
    public static function buildFilter($filter)
225 1
    {
226 1
        $key = array_keys($filter)[0];
227 1
        $value = $filter[$key];
228 1
        $operator = ' = ';
229
        $method = 'eq';
230 1
231 1
        $methods = [
232 1
            'gte'   => 'gte',
233 1
            'gt'    => 'gt',
234 1
            'lte'   => 'lte',
235 1
            'lt'    => 'lt',
236 1
            'in'    => 'in',
237 1
            '!in'   => 'notIn',
238 1
            'not'   => 'not',
239 1
            'wildchard' => 'like',
240
            'prefix' => 'like',
241 1
        ];
242 1
        $operands = [
243 1
            'gte'   => ' >= ',
244 1
            'gt'    => ' > ',
245 1
            'lte'   => ' <= ',
246 1
            'lt'    => ' < ',
247
            'in'    => ' IN ',
248 1
            '!in'   => ' NOT IN',
249
            'not'   => ' NOT',
250
            'wildchard' => ' LIKE ',
251 1
            'prefix' => ' LIKE ',
252
        ];
253
254
        if (strpos($key, '__')!==false) {
255 1
            preg_match('/__(.*?)$/i', $key, $matches);
256
            $key        = str_replace($matches[0], '', $key);
257 1
            $operator   = $matches[1];
258 1
            $method     = $methods[$operator];
259 1
            $operator   = $operands[$operator];
260
            switch ($operator) {
261 1
                case 'wildcard':
262
                    $value = str_replace(array('?', '*'), array('_', '%'), $value);
263
                    break;
264
                case 'prefix':
265
                    $value = $value.'%';
266
                    break;
267
            }
268
        }
269
        return [
270
            'key'       => $key,
271
            'operand'   => $operator,
272
            'method'    => $method,
273
            'value'     => $value
274
        ];
275
276
    }
277
278
279
}
280