Completed
Push — master ( 2e405d...fdbb40 )
by Mehmet
06:00
created

SQL::find()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 29
Code Lines 23

Duplication

Lines 6
Ratio 20.69 %

Code Coverage

Tests 19
CRAP Score 8.2746

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 6
loc 29
ccs 19
cts 27
cp 0.7037
rs 6.7272
cc 7
eloc 23
nc 5
nop 7
crap 8.2746
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 3
    public function __construct($config, Connection $client)
29
    {
30 3
        $this->conn = $client;
31 3
        $this->dbName = $config['db_name'];
32 3
    }
33
34 1
    public function getConnection()
35
    {
36 1
        return $this->conn;
37
    }
38
39 3
    public function create($collection, $fields)
40
    {
41 3
        $columns = [];
42 3
        $indexes = [];
43 3
        $schemaManager = $this->conn->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
63 3
            $columns[] = new Column($field['name'], Type::getType($field['type']), $options );
64 3
        }
65 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...
66 3
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
67 3
        }
68 3
        $table = new Table($collection, $columns, $indexes);
69 3
        return $schemaManager->createTable($table);
70
    }
71
72 3
    public function drop($collection)
73
    {
74 3
        $schemaManager = $this->conn->getSchemaManager();
75 3
        if ($schemaManager->tablesExist([$collection])) {
76 2
            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 3
    public function insert($collection, $values)
113
    {
114 3
        $insertion = $this->conn->insert($collection, $values);
115 3
        if($insertion !== 0) {
116 3
            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 1
    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
                    $queryBuilder->addOrderBy($sort_key, $sort_dir);
159
                }
160
            }
161 1
            $queryBuilder->select($fields)
162 1
                ->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 1
        return ['total' => $numberOfSet, 'data' => $result];
168
    }
169
170 3
    public function buildQuery($collection, $filters)
171
    {
172 2
        $queryBuilder = $this->conn->createQueryBuilder();
173 2
        $queryBuilder->from($collection);
174 3
        if ($filters !== null) {
175 2
            foreach ($filters as $key => $value) {
176 2
                if (strpos($key, '__') === false && is_array($value)) {
177 2
                    $orQuery =[];
178 2
                    foreach ($value as $orValue) {
179 2
                        $subKey = array_keys($orValue)[0];
180 2
                        $subValue = $orValue[$subKey];
181 2
                        $sqlOptions = self::buildFilter([$subKey => $subValue]);
182 2
                        if(in_array($sqlOptions['method'], ['in', 'notIn'])){
183 1
                            $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value']);
184 1
                        }
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 2
                            $orQuery[] =
187 2
                                '`'.$sqlOptions['key'].'`'
188 2
                                . ' ' . $sqlOptions['operand']
189 2
                                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
190
                        }
191 2
                    }
192
193 2
                    $queryBuilder->andWhere(
194 2
                        implode(' OR ', $orQuery)
195 2
                    );
196 2
                } else {
197 2
                    $sqlOptions = self::buildFilter([$key=>$value]);
198 2
                    if(in_array($sqlOptions['method'], ['in', 'notIn', ''])){
199
                        $queryBuilder->andWhere(
200
                            $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
201
                        );
202
                    }
203 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 2
                        $queryBuilder->andWhere(
205 2
                            '`'.$sqlOptions['key'].'`'
206 2
                            . ' ' . $sqlOptions['operand']
207 2
                            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
208 2
                        );
209
                    }
210
                }
211 2
            }
212 2
        }
213
214 2
        return $queryBuilder;
215
    }
216
217
218
219 1
    public function query($collection)
220
    {
221 1
        return new SQLQueryBuilder($collection, $this);
222
    }
223
224 2
    public static function buildFilter($filter)
225
    {
226 2
        $key = array_keys($filter)[0];
227 2
        $value = $filter[$key];
228 2
        $operator = ' = ';
229 2
        $method = 'eq';
230
231
        $methods = [
232 2
            'gte'   => 'gte',
233 2
            'gt'    => 'gt',
234 2
            'lte'   => 'lte',
235 2
            'lt'    => 'lt',
236 2
            'in'    => 'in',
237 2
            '!in'   => 'notIn',
238 2
            'not'   => 'not',
239 2
            'wildchard' => 'like',
240 2
            'prefix' => 'like',
241 2
        ];
242
        $operands = [
243 2
            'gte'   => ' >= ',
244 2
            'gt'    => ' > ',
245 2
            'lte'   => ' <= ',
246 2
            'lt'    => ' < ',
247 2
            'in'    => ' IN ',
248 2
            '!in'   => ' NOT IN',
249 2
            'not'   => ' NOT',
250 2
            'wildchard' => ' LIKE ',
251 2
            'prefix' => ' LIKE ',
252 2
        ];
253
254 2
        if (strpos($key, '__')!==false) {
255 2
            preg_match('/__(.*?)$/i', $key, $matches);
256 2
            $key        = str_replace($matches[0], '', $key);
257 2
            $operator   = $matches[1];
258 2
            $method     = $methods[$operator];
259 2
            $operator   = $operands[$operator];
260
            switch ($operator) {
261 2
                case 'wildcard':
262
                    $value = str_replace(array('?', '*'), array('_', '%'), $value);
263
                    break;
264 2
                case 'prefix':
265
                    $value = $value.'%';
266
                    break;
267
            }
268 2
        }
269
        return [
270 2
            'key'       => $key,
271 2
            'operand'   => $operator,
272 2
            'method'    => $method,
273
            'value'     => $value
274 2
        ];
275
276
    }
277
278
279
}
280