Completed
Push — master ( d114d5...d4e813 )
by Mehmet
02:48
created

SQL::createAddColumns()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 22
Code Lines 15

Duplication

Lines 7
Ratio 31.82 %

Code Coverage

Tests 16
CRAP Score 6.0493

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 7
loc 22
ccs 16
cts 18
cp 0.8889
rs 8.6737
cc 6
eloc 15
nc 7
nop 3
crap 6.0493
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
48 3
        $columns = $this->createAddColumns($collection, $columns, $fields);
49
50 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...
51
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
52
        }
53 3
        $table = new Table($collection, $columns, $indexes);
54 3
        return $schemaManager->createTable($table);
55
    }
56
57 3
    protected function createAddColumns($collection, $columns, $fields)
58
    {
59 3
        foreach ($fields as $field){
60 3
            $field = array_merge(self::$columnDefaults, $field);
61 3
            $options = [];
62 3
            if ($field['type'] == 'integer' && $field['type_info'] == 'unsigned') {
63
                $options['unsigned'] = true;
64
            }
65 3
            $options['length'] = $field['maxLength'];
66 3
            $options['default'] = $field['default'];
67 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...
68 3
                if ( $field['index_type'] == 'unique' ) {
69 3
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indexes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indexes = 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...
70 3
                } else {
71 3
                    $tmpIndexes[] = $field['name'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tmpIndexes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tmpIndexes = 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...
72
                }
73 3
            }
74 3
            $columns[] = new Column($field['name'], Type::getType($field['type']), $options );
75 3
        }
76
77 3
        return $columns;
78
    }
79
80 3
    public function drop($collection)
81
    {
82 3
        $schemaManager = $this->doctrine->getSchemaManager();
83 3
        if ($schemaManager->tablesExist([$collection])) {
84 2
            return $schemaManager->dropTable($collection);
85
        } else {
86 1
            return null;
87
        }
88
    }
89
90
    public function truncate($collection)
91
    {
92
        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...
93
    }
94
95
    public function createIndexes($collection, $indexes)
96
    {
97
        $schemaManager = $this->doctrine->getSchemaManager();
98
        $tmpIndexes = [];
99
        foreach ($indexes as $field){
100
            $field = array_merge(self::$columnDefaults, $field);
101 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...
102
                if ( $field['index_type'] == 'unique' ) {
103
                    $indexes[] = new Index($collection . '_' . $field['name'] . '_UNQ', [$field['name']], true, false);
104
                } else {
105
                    $tmpIndexes[] = $field['name'];
106
                }
107
            }
108
        }
109 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...
110
            $indexes[] = new Index($collection . '_IDX', $tmpIndexes, false, false);
111
        }
112
        foreach ($indexes as $index) {
113
            $schemaManager->createIndex($index, $collection);
114
        }
115
    }
116
117 3
    public function insert($collection, $values)
118
    {
119 3
        $insertion = $this->doctrine->insert($collection, $values);
120 3
        if($insertion !== 0) {
121 3
            return $this->doctrine->lastInsertId();
122
        }
123
        return null;
124
    }
125
126
    public function update($collection, $filter, $values)
127
    {
128
        return $this->doctrine->update($collection, $values, $filter);
129
    }
130
131 2
    public function delete($collection, $filter)
132
    {
133 2
        $numberOfDeletedItems = $this->doctrine->delete($collection, $filter);
134 2
        if ($numberOfDeletedItems>0) {
135 2
            return 1;
136
        }
137
        return 0;
138
    }
139
140 1
    public function get($collection, $docId)
141
    {
142 1
        return $this->doctrine->fetchAssoc('SELECT * FROM ' . $collection . ' WHERE id = ?', array($docId));
143
    }
144
145 1
    public function find($collection, $filters, $fields = null, $sort = null, $offset = 0, $limit = 25, $debug = false)
146
    {
147 1
        $query = $this->query($collection);
148 1
        foreach ($filters as $filter => $value) {
149 1
            if (is_array($value)) {
150 1
                $query->orFilters($value);
151 1
            } else {
152 1
                $query->andFilter($filter, $value);
153
            }
154 1
        }
155 1
        return $query->returnFields($fields)
156 1
            ->sortFields($sort)
157 1
            ->offset($offset)
158 1
            ->limit($limit)
159 1
            ->run();
160
    }
161
162 2
    public function buildQuery($collection, $filters)
163
    {
164 2
        $queryBuilder = $this->doctrine->createQueryBuilder();
165 2
        $queryBuilder->from($collection);
166 2
        if ($filters === null) {
167
            return $queryBuilder;
168
        }
169 2
        return $this->buildQueryFilters($queryBuilder, $filters);
170
    }
171
172 3
    protected function buildQueryFilters($queryBuilder, $filters)
173
    {
174 3
        foreach ($filters as $key => $value) {
175 2
            if (strpos($key, '__') === false && is_array($value)) {
176 2
                $queryBuilder = $this->buildQueryForOr($queryBuilder, $value);
177 2
                continue;
178
            }
179 2
            $queryBuilder = $this->buildQueryForAnd($queryBuilder, $key, $value);
180 2
        }
181 2
        return $queryBuilder;
182
    }
183
184 2
    protected function buildQueryForAnd($queryBuilder, $key, $value)
185
    {
186 2
        $sqlOptions = self::buildFilter([$key => $value]);
187 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...
188
            $queryBuilder->andWhere(
189
                $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
190
            );
191
            return $queryBuilder;
192
        }
193 2
        $queryBuilder->andWhere(
194 2
                '`'.$sqlOptions['key'].'`'
195 2
                . ' ' . $sqlOptions['operand']
196 2
                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
197 2
            );
198 2
        return $queryBuilder;
199
    }
200 2
    protected function buildQueryForOr($queryBuilder, $value)
201
    {
202 2
        $orQuery =[];
203 2
        foreach ($value as $orValue) {
204 2
            $subKey = array_keys($orValue)[0];
205 2
            $subValue = $orValue[$subKey];
206 2
            $sqlOptions = self::buildFilter([$subKey => $subValue]);
207 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...
208 1
                $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value']);
209 1
                continue;
210
            }
211 2
            $orQuery[] =
212 2
                '`'.$sqlOptions['key'].'`'
213 2
                . ' ' . $sqlOptions['operand']
214 2
                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
215
216 2
        }
217 2
        $queryBuilder->andWhere(
218 2
            '(' . implode(' OR ', $orQuery) . ')'
219 2
        );
220 2
        return $queryBuilder;
221
    }
222
223 2
    public function query($collection)
224
    {
225 2
        return new SQLQueryBuilder($collection, $this);
226
    }
227
228 2
    public static function buildFilter($filter)
229
    {
230 2
        $key = array_keys($filter)[0];
231 2
        $value = $filter[$key];
232 2
        $operator = ' = ';
233 2
        $method = 'eq';
234
        $options =[
235 2
            'gte'       => ['method' => 'gte', 'operand' => ' >= '],
236 2
            'gt'        => ['method' => 'gt', 'operand' => ' > '],
237 2
            'lte'       => ['method' => 'lte', 'operand' => ' <= '],
238 2
            'lt'        => ['method' => 'lt', 'operand' => ' < '],
239 2
            'in'        => ['method' => 'in', 'operand' => ' IN '],
240 2
            '!in'       => ['method' => 'notIn', 'operand' => ' NOT IN '],
241 2
            'not'       => ['method' => 'not', 'operand' => ' NOT '],
242 2
            'wildcard'  => ['method' => 'like', 'operand' => ' LIKE '],
243 2
            'prefix'    => ['method' => 'like', 'operand' => ' LIKE '],
244 2
        ];
245 2
        if (strpos($key, '__') !== false) {
246 2
            preg_match('/__(.*?)$/i', $key, $matches);
247 2
            $key        = str_replace($matches[0], '', $key);
248 2
            $queryOperator   = $matches[1];
249 2
            $method     = $options[$queryOperator]['method'];
250 2
            $operator   = $options[$queryOperator]['operand'];
251
            switch ($queryOperator) {
252 2
                case 'wildcard':
253 1
                    $value = '%'.str_replace(array('?', '*'), array('_', '%'), $value).'%';
254 1
                    break;
255 2
                case 'prefix':
256 1
                    $value = $value.'%';
257 1
                    break;
258
            }
259 2
        }
260
        return [
261 2
            'key'       => $key,
262 2
            'operand'   => $operator,
263 2
            'method'    => $method,
264
            'value'     => $value
265 2
        ];
266
    }
267
268
}
269