Completed
Push — master ( 188d30...be044a )
by Mehmet
03:55
created

SQL::find()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 7
Bugs 2 Features 0
Metric Value
c 7
b 2
f 0
dl 0
loc 16
ccs 12
cts 12
cp 1
rs 9.4285
cc 3
eloc 12
nc 3
nop 7
crap 3
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 1
    public function getConnection()
35
    {
36 1
        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
            $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 3
    }
70
71
    public function drop($collection)
72 3
    {
73
        $schemaManager = $this->doctrine->getSchemaManager();
74 3
        if ($schemaManager->tablesExist([$collection])) {
75 3
            return $schemaManager->dropTable($collection);
76 2
        } else {
77
            return null;
78 1
        }
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
    public function insert($collection, $values)
109
    {
110
        $insertion = $this->doctrine->insert($collection, $values);
111
        if($insertion !== 0) {
112 3
            return $this->doctrine->lastInsertId();
113
        }
114 3
        return null;
115 3
    }
116 3
117
    public function update($collection, $filter, $values)
118
    {
119
        return $this->doctrine->update($collection, $values, $filter);
120
    }
121
122
    public function delete($collection, $filter)
123
    {
124
        $numberOfDeletedItems = $this->doctrine->delete($collection, $filter);
125
        if ($numberOfDeletedItems>0) {
126 2
            return 1;
127
        }
128 2
        return 0;
129 2
    }
130 2
131
    public function get($collection, $docId)
132
    {
133
        return $this->doctrine->fetchAssoc('SELECT * FROM '.$collection.' WHERE id = ?', array($docId));
134
    }
135 1
136
    public function find($collection, $filters, $fields = null, $sort = null, $offset = 0, $limit = 25, $debug = false)
137 1
    {
138
        $query = $this->query($collection);
139
        foreach ($filters as $filter => $value) {
140 1
            if (is_array($value)) {
141
                $query->orFilters([$value]);
142 1
            } else {
143 1
                $query->andFilter($filter, $value);
144 1
            }
145 1
        }
146 1
        return $query->returnFields($fields)
147 1
            ->sortFields($sort)
148 1
            ->offset($offset)
149 1
            ->limit($limit)
150 1
            ->run();
151 1
    }
152 1
153
    public function buildQuery($collection, $filters)
154
    {
155
        $queryBuilder = $this->doctrine->createQueryBuilder();
156
        $queryBuilder->from($collection);
157
        if ($filters !== null) {
158
            foreach ($filters as $key => $value) {
159
                if (strpos($key, '__') === false && is_array($value)) {
160
                    $orQuery =[];
161 1
                    foreach ($value as $orValue) {
162 1
                        $subKey = array_keys($orValue)[0];
163 1
                        $subValue = $orValue[$subKey];
164 1
                        $sqlOptions = self::buildFilter([$subKey => $subValue]);
165 1
                        if (in_array($sqlOptions['method'], ['in', 'notIn'])) {
166 1
                            $orQuery[] =  $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value']);
167 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...
168
                            $orQuery[] =
169
                                '`'.$sqlOptions['key'].'`'
170 3
                                . ' ' . $sqlOptions['operand']
171
                                . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value']);
172 2
                        }
173 2
                    }
174 3
                    $queryBuilder->andWhere(
175 2
                        '(' . implode(' OR ', $orQuery) . ')'
176 2
                    );
177 2
                } else {
178 2
                    $sqlOptions = self::buildFilter([$key=>$value]);
179 2
                    if (in_array($sqlOptions['method'], ['in', 'notIn'])) {
180 2
                        $queryBuilder->andWhere(
181 2
                            $queryBuilder->expr()->{$sqlOptions['method']}( $sqlOptions['key'], $sqlOptions['value'])
182 2
                        );
183 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...
184 1
                        $queryBuilder->andWhere(
185
                            '`'.$sqlOptions['key'].'`'
186 2
                            . ' ' . $sqlOptions['operand']
187 2
                            . ' ' . $queryBuilder->createNamedParameter($sqlOptions['value'])
188 2
                        );
189 2
                    }
190
                }
191 2
            }
192 2
        }
193 2
        return $queryBuilder;
194 2
    }
195 2
196 2
    public function query($collection)
197 2
    {
198
        return new SQLQueryBuilder($collection, $this);
199
    }
200
201
    public static function buildFilter($filter)
202
    {
203 2
        $key = array_keys($filter)[0];
204 2
        $value = $filter[$key];
205 2
        $operator = ' = ';
206 2
        $method = 'eq';
207 2
        $options =[
208
            'gte'       => ['method' => 'gte', 'operand' => ' >= '],
209
            'gt'        => ['method' => 'gt', 'operand' => ' > '],
210 2
            'lte'       => ['method' => 'lte', 'operand' => ' <= '],
211 2
            'lt'        => ['method' => 'lt', 'operand' => ' < '],
212 2
            'in'        => ['method' => 'in', 'operand' => ' IN '],
213
            '!in'       => ['method' => 'notIn', 'operand' => ' NOT IN '],
214
            'not'       => ['method' => 'not', 'operand' => ' NOT '],
215
            'wildcard'  => ['method' => 'like', 'operand' => ' LIKE '],
216
            'prefix'    => ['method' => 'like', 'operand' => ' LIKE '],
217 1
        ];
218
        if (strpos($key, '__') !== false) {
219 1
            preg_match('/__(.*?)$/i', $key, $matches);
220
            $key        = str_replace($matches[0], '', $key);
221
            $operator   = $matches[1];
222 2
            $method     = $options[$operator]['method'];
223
            $operator   = $options[$operator]['operand'];
224 2
            switch ($operator) {
225 2
                case 'wildcard':
226 2
                    $value = str_replace(array('?', '*'), array('_', '%'), $value);
227 2
                    break;
228
                case 'prefix':
229
                    $value = $value.'%';
230 2
                    break;
231 2
            }
232 2
        }
233 2
        return [
234 2
            'key'       => $key,
235 2
            'operand'   => $operator,
236 2
            'method'    => $method,
237 2
            'value'     => $value
238 2
        ];
239 2
    }
240
241
}
242