Passed
Push — master ( f0f6bb...8d042a )
by Dāvis
02:47
created

QuickInsertRepository   F

Complexity

Total Complexity 92

Size/Duplication

Total Lines 387
Duplicated Lines 3.1 %

Importance

Changes 0
Metric Value
dl 12
loc 387
rs 1.5789
c 0
b 0
f 0
wmc 92

17 Methods

Rating   Name   Duplication   Size   Complexity  
B isEmpty() 0 13 5
C buildExtra() 0 38 8
A extract() 0 8 1
B extractExt() 0 24 4
B init() 0 18 5
A close() 0 4 2
C update() 9 64 16
A runSQL() 0 10 2
A value() 0 6 2
A findNextIdExt() 0 6 1
A findNextId() 0 12 2
A link() 0 6 1
C persist() 3 60 19
D get() 0 27 9
A delete() 0 7 1
A getTable() 0 13 4
C buildWhere() 0 24 10

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 QuickInsertRepository 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.

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 QuickInsertRepository, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Sludio\HelperBundle\Script\Repository;
4
5
class QuickInsertRepository
6
{
7
    private static $mock = [];
8
    private static $metadata = [];
9
    private static $tableName;
10
11
    public static $entityManager;
12
    public static $connection;
13
14
    public static function init($noFkCheck = false, $manager = null)
15
    {
16
        if (self::$connection) {
17
            return;
18
        }
19
        global $kernel;
20
21
        if ('AppCache' === get_class($kernel)) {
22
            $kernel = $kernel->getKernel();
23
        }
24
        $container = $kernel->getContainer();
25
26
        $manager = $manager ?: $container->getParameter('sludio_helper.entity.manager');
27
        self::$entityManager = $container->get('doctrine')->getManager($manager);
28
        self::$connection = self::$entityManager->getConnection();
29
30
        if (!$noFkCheck) {
31
            self::runSQL('SET FOREIGN_KEY_CHECKS = 0');
32
        }
33
    }
34
35
    public static function close($noFkCheck = false)
36
    {
37
        if (!$noFkCheck) {
38
            self::runSQL('SET FOREIGN_KEY_CHECKS = 1');
39
        }
40
    }
41
42
    public static function isEmpty($variable)
43
    {
44
        $result = true;
45
46
        if (is_array($variable) && count($variable) > 0) {
47
            foreach ($variable as $value) {
48
                $result = $result && self::isEmpty($value);
49
            }
50
        } else {
51
            $result = empty($variable);
52
        }
53
54
        return $result;
55
    }
56
57
    private static function extract($object)
58
    {
59
        self::init(false);
60
        $data = self::extractExt($object, self::$entityManager);
61
62
        self::$mock = $data['mock'];
63
        self::$tableName = $data['table'];
64
        self::$metadata[$data['table']] = $data['meta'];
65
    }
66
67
    public static function extractExt($object, $entityManager)
68
    {
69
        $metadata = $entityManager->getClassMetadata(get_class($object));
70
71
        $fields = $metadata->getFieldNames();
72
        $columns = $metadata->getColumnNames();
73
        $table = $metadata->getTableName();
74
75
        $result = [];
76
        foreach ($fields as $key => $field) {
77
            foreach ($columns as $key2 => $column) {
78
                if ($key === $key2) {
79
                    $result[$table][$field] = $column;
80
                }
81
            }
82
        }
83
84
        $data = [
85
            'mock' => $result,
86
            'table' => $table,
87
            'meta' => $metadata,
88
        ];
89
90
        return $data;
91
    }
92
93
    private static function buildExtra($extra)
94
    {
95
        $methods = [
96
            'GROUP BY',
97
            'HAVING',
98
            'ORDER BY',
99
        ];
100
        $sql = '';
101
102
        foreach ($methods as $method) {
103
            if (isset($extra[$method])) {
104
                $sql .= ' '.$method.' ';
105
                if (is_array($extra[$method])) {
106
                    foreach ($extra[$method] as $group) {
107
                        $sql .= $group.' ';
108
                    }
109
                } else {
110
                    $sql .= $extra[$method].' ';
111
                }
112
            }
113
        }
114
115
        if (isset($extra['LIMIT'])) {
116
            if (is_array($extra['LIMIT'])) {
117
                if (isset($extra['LIMIT'][1])) {
118
                    $offset = $extra['LIMIT'][0];
119
                    $limit = $extra['LIMIT'][1];
120
                } else {
121
                    $offset = 0;
122
                    $limit = $extra['LIMIT'][0];
123
                }
124
                $sql .= 'LIMIT '.$offset.', '.$limit;
125
            }
126
        }
127
128
        $sql = str_replace('  ', ' ', $sql);
129
130
        return $sql;
131
    }
132
133
    private static function buildWhere($tableName, $where)
134
    {
135
        $whereSql = '';
136
        if (is_array($where) && !empty($where)) {
137
            reset($where);
138
            $first = key($where);
139
            $path = ' WHERE ';
140
            foreach ($where as $key => $value) {
141
                if (!is_array($value) && isset(self::$mock[$tableName][$key])) {
142
                    $whereSql .= $path.self::$mock[$tableName][$key]." = ".(is_numeric($value) ? $value : "'".addslashes(trim($value))."'");
143
                } else {
144
                    if (is_array($value)) {
145
                        $whereSql .= $path.$value[0];
146
                    } else {
147
                        $whereSql .= $path.$key." = ".(is_numeric($value) ? $value : "'".addslashes(trim($value))."'");
148
                    }
149
                }
150
                if ($key === $first) {
151
                    $path = ' AND ';
152
                }
153
            }
154
        }
155
156
        return $whereSql;
157
    }
158
159
    private static function getTable(&$object, &$tableName, &$columns, &$type, $noFkCheck = true, $manager = null)
160
    {
161
        self::init($noFkCheck, $manager);
162
        if (is_object($object)) {
163
            self::extract($object);
164
            $tableName = self::$tableName;
165
            $columns = self::$mock[$tableName] ?: [];
166
            $type = 'object';
167
        } else {
168
            $tableName = $object['table_name'];
169
            unset($object['table_name']);
170
            $type = 'table';
171
            $columns = array_keys($object) ?: [];
172
        }
173
    }
174
175
    public static function findNextId($tableName)
176
    {
177
        $result = self::get(['table_name' => 'information_schema.tables'], true, [
178
            'table_name' => $tableName,
179
            ['table_schema = DATABASE()'],
180
        ], true, ['AUTO_INCREMENT'], null, []);
181
182
        if ($result) {
183
            return $result;
184
        }
185
186
        return 1;
187
    }
188
189
    public static function findNextIdExt($object, $entityManager = null)
190
    {
191
        self::init(true);
192
        $data = self::extractExt($object, $entityManager);
193
194
        return self::findNextId($data['table']);
195
    }
196
197
    public static function runSQL($sql, $noFkCheck = true, $manager = null)
198
    {
199
        $sql = trim(preg_replace('/\s+/', ' ', $sql));
200
        self::init($noFkCheck, $manager);
201
        $sth = self::$connection->prepare($sql);
202
        $sth->execute();
203
204
        self::close($noFkCheck);
205
        if (substr($sql, 0, 6) === "SELECT") {
206
            return $sth->fetchAll();
207
        }
208
    }
209
210
    public static function get($object, $one = false, $where = [], $noFkCheck = true, $fields = [], $manager = null, $extra = [])
211
    {
212
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
213
214
        $select = (isset($extra['MODE']) ? 'SELECT '.$extra['MODE'] : 'SELECT').' ';
215
        $fields = $fields ?: ['id'];
216
        $sql = $select.(implode(', ', $fields)).' FROM '.$tableName.self::buildWhere($tableName, $where).self::buildExtra($extra);
217
218
        $result = self::runSQL($sql);
219
220
        if ($result) {
221
            $field = null;
222
            if (count($fields) === 1 && $fields[0] !== '*') {
223
                $field = $fields[0];
224
            }
225
            if ($field) {
226
                if (!$one) {
227
                    foreach ($result as &$res) {
228
                        $res = $res[$field];
229
                    }
230
                } else {
231
                    $result = $result[0];
232
                }
233
            }
234
        }
235
236
        return $result;
237
    }
238
239
    private static function value($object, $variable, $type)
240
    {
241
        if ($type === 'object') {
242
            return $object->{'get'.ucfirst($variable)}();
243
        } else {
244
            return $object[$variable];
245
        }
246
    }
247
248
    public static function persist($object, $full = false, $extraFields = [], $noFkCheck = false, $manager = null)
249
    {
250
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
251
252
        $id = self::findNextId($tableName);
253
        $keys = $values = [];
254
255 View Code Duplication
        if (!empty($extraFields) && isset($extraFields[$tableName])) {
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...
256
            $columns = array_merge($columns, $extraFields[$tableName]);
257
        }
258
259
        $idd = null;
260
        foreach ($columns as $value => $key) {
261
            $variable = null;
262
            if (!is_array($key) && !is_array($value)) {
263
                $value = self::value($object, $value, $type);
264
                if ($value instanceof \DateTime) {
265
                    $variable = "'".addslashes(trim($value->format('Y-m-d H:i:s')))."'";
266
                } else {
267
                    $variable = "'".addslashes(trim($value))."'";
268
                }
269
                if (trim($variable) === '' || trim($variable) === "''" || (is_numeric($variable) && $variable === 0)) {
270
                    $variable = null;
271
                }
272
                if ($variable !== null) {
273
                    $values[] = $variable;
274
                    $keys[] = $key;
275
                    if ($key === 'id') {
276
                        $idd = $value;
277
                    }
278
                }
279
            }
280
        }
281
282
        $sql = null;
283
        if (!$full && !self::isEmpty($values)) {
284
            $sql = '
285
                INSERT INTO
286
                    '.$tableName.'
287
                        (id, '.implode(',', $keys).")
288
                VALUES
289
                    ({$id},".implode(',', $values).')
290
            ';
291
        } elseif ($full && !self::isEmpty($values)) {
292
            $id = $idd;
293
            $sql = '
294
                INSERT INTO
295
                    '.$tableName.'
296
                        ('.implode(',', $keys).")
297
                VALUES
298
                    (".implode(',', $values).')
299
            ';
300
        } else {
301
            $id = null;
302
        }
303
        if ($sql !== null && $id !== null) {
304
            self::runSQL($sql);
305
        }
306
307
        return $id;
308
    }
309
310
    public static function update($id, $object, $extraFields = [], $noFkCheck = false, $manager = null)
311
    {
312
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
313
314
        $result = self::get(['table_name' => $tableName], true, ['id' => $id], true, ['*']);
315
        unset($result['id']);
316
317
        $data = [];
318
319 View Code Duplication
        if (!empty($extraFields) && isset($extraFields[$tableName])) {
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...
320
            $columns = array_merge($columns, $extraFields[$tableName]);
321
        }
322
323
        $flip = array_flip($columns);
324
        if ($type === 'object') {
325
            if ($id) {
326
                foreach ($result as $key => $value) {
327 View Code Duplication
                    if ($object->{'get'.ucfirst($flip[$key])}() !== $value) {
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...
328
                        $data[$columns[$flip[$key]]] = $object->{'get'.ucfirst($flip[$key])}();
329
                    }
330
                }
331
            } else {
332
                foreach ($result as $key => $value) {
333
                    if ($object->{'get'.ucfirst($flip[$key])}() !== null) {
334 View Code Duplication
                        if ($object->{'get'.ucfirst($flip[$key])}() !== $value) {
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...
335
                            $data[$columns[$flip[$key]]] = $object->{'get'.ucfirst($flip[$key])}();
336
                        }
337
                    }
338
                }
339
            }
340
        } else {
341
            foreach ($result as $key => $value) {
342
                if (isset($object[$key]) && $object[$key] !== $value) {
343
                    $data[$key] = $extraFields[$key];
344
                }
345
            }
346
347
        }
348
349
        if ($data) {
350
            $sql = "
351
                UPDATE
352
                    ".$tableName."
353
                SET
354
355
            ";
356
            foreach ($data as $key => $value) {
357
                $meta = self::$metadata[$tableName]->getFieldMapping($flip[$key]);
358
                $meta = $meta['type'];
359
                if (in_array($meta, [
360
                    'boolean',
361
                    'integer',
362
                    'longint',
363
                ])) {
364
                    $value = intval($value);
365
                } else {
366
                    $value = "'".addslashes(trim($value))."'";
367
                }
368
                $sql .= " ".$key." = ".$value.",";
369
            }
370
            $sql = substr($sql, 0, -1);
371
            $sql .= " WHERE id = ".$id;
372
373
            self::runSQL($sql);
374
        }
375
    }
376
377
    public static function delete($object, $where = [], $noFkCheck = false, $manager = null)
378
    {
379
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
380
381
        $whereSql = self::buildWhere($tableName, $where);
382
        $sql = 'DELETE FROM '.$tableName.' '.$whereSql;
383
        self::runSQL($sql);
384
    }
385
386
    public static function link($object, $data, $noFkCheck = false, $manager = null)
387
    {
388
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
389
390
        $data['table_name'] = $tableName;
391
        self::persist($data, true, [], $noFkCheck, $manager);
392
    }
393
}
394