Passed
Push — master ( 39a592...c8460b )
by Dāvis
02:48
created

QuickInsertRepository   F

Complexity

Total Complexity 87

Size/Duplication

Total Lines 383
Duplicated Lines 3.39 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 13
loc 383
rs 1.5789
wmc 87

18 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 buildWhere() 0 24 10
C update() 0 42 8
A runSQL() 0 10 2
B value() 0 23 5
A findNextIdExt() 0 6 1
A findNextId() 0 12 2
A link() 6 6 1
D persist() 0 44 10
C get() 0 29 11
A delete() 6 6 1
B variable() 0 10 5
B getTable() 0 17 6

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, $extraFields = [])
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
        if (!empty($extraFields) && isset($extraFields[$tableName])) {
175
            $columns = array_merge($columns, $extraFields[$tableName]);
176
        }
177
    }
178
179
    public static function findNextId($tableName)
180
    {
181
        $result = self::get(['table_name' => 'information_schema.tables'], true, [
182
            'table_name' => $tableName,
183
            ['table_schema = DATABASE()'],
184
        ], true, ['AUTO_INCREMENT'], null, []);
185
186
        if ($result) {
187
            return $result;
188
        }
189
190
        return 1;
191
    }
192
193
    public static function findNextIdExt($object, $entityManager = null)
194
    {
195
        self::init(true);
196
        $data = self::extractExt($object, $entityManager);
197
198
        return self::findNextId($data['table']);
199
    }
200
201
    public static function runSQL($sql, $noFkCheck = true, $manager = null)
202
    {
203
        $sql = trim(preg_replace('/\s+/', ' ', $sql));
204
        self::init($noFkCheck, $manager);
205
        $sth = self::$connection->prepare($sql);
206
        $sth->execute();
207
208
        self::close($noFkCheck);
209
        if (substr($sql, 0, 6) === "SELECT") {
210
            return $sth->fetchAll();
211
        }
212
    }
213
214
    public static function get($object, $one = false, $where = [], $noFkCheck = true, $fields = [], $manager = null, $extra = [])
215
    {
216
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
217
218
        $select = (isset($extra['MODE']) ? 'SELECT '.$extra['MODE'] : 'SELECT').' ';
219
        $fields = $fields ?: ['id'];
220
        $sql = $select.(implode(', ', $fields)).' FROM '.$tableName.self::buildWhere($tableName, $where).self::buildExtra($extra);
221
222
        $result = self::runSQL($sql) ?: null;
223
224
        if ($result) {
225
            $field = null;
226
            if (count($fields) === 1 && $fields[0] !== '*') {
227
                $field = $fields[0];
228
            }
229
            if ($field) {
230
                if (!$one) {
231
                    foreach ($result as &$res) {
232
                        $res = $res[$field];
233
                    }
234
                } else {
235
                    $result = $result[0][$field];
236
                }
237
            } elseif ($one) {
238
                $result = $result[0];
239
            }
240
        }
241
242
        return $result;
243
    }
244
245
    private static function variable(&$value)
246
    {
247
        if ($value instanceof \DateTime) {
248
            $value = "'".addslashes(trim($value->format('Y-m-d H:i:s')))."'";
249
        } elseif (!is_numeric($value)) {
250
            $value = "'".addslashes(trim($value))."'";
251
        }
252
253
        if (trim($value) === '' || trim($value) === "''") {
254
            $value = null;
255
        }
256
    }
257
258
    private static function value($object, $variable, $type, $check = true)
259
    {
260
        $value = null;
261
        if ($type === 'object') {
262
263
            $variables = explode('_', $variable);
264
            foreach ($variables as &$var) {
265
                $var = ucfirst($var);
266
            }
267
            $variable = implode('', $variables);
268
269
            $value = $object->{'get'.ucfirst($variable)}();
270
        } else {
271
            if (isset($object[$variable])) {
272
                $value = $object[$variable];
273
            }
274
        }
275
276
        if ($check) {
277
            self::variable($value);
278
        }
279
280
        return $value;
281
    }
282
283
    public static function persist($object, $full = false, $extraFields = [], $noFkCheck = false, $manager = null)
284
    {
285
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager, $extraFields);
286
287
        $id = self::findNextId($tableName);
288
        $data = [];
289
290
        $idd = null;
291
        foreach ($columns as $value => $key) {
292
            if (!is_array($key) && !is_array($value)) {
293
                $value = self::value($object, $value, $type);
294
                if ($value !== null) {
295
                    $data[$key] = $value;
296
                    if ($key === 'id') {
297
                        $idd = $value;
298
                    }
299
                }
300
            }
301
        }
302
303
        $sql = null;
304
        if (!$full) {
305
            $data['id'] = $id;
306
        } else {
307
            $id = $idd;
308
        }
309
310
        if (!self::isEmpty($data)) {
311
            $sql = '
312
                INSERT INTO
313
                    '.$tableName.'
314
                        ('.implode(',', array_keys($data)).')
315
                VALUES
316
                    ('.implode(',', array_values($data)).')
317
            ';
318
        } else {
319
            $id = null;
320
        }
321
322
        if ($sql !== null && $id !== null) {
323
            self::runSQL($sql);
324
        }
325
326
        return $id;
327
    }
328
329
    public static function update($id, $object, $extraFields = [], $noFkCheck = false, $manager = null)
330
    {
331
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager, $extraFields);
332
333
        $result = self::get(['table_name' => $tableName], true, ['id' => $id], true, ['*']);
334
        unset($result['id']);
335
        $data = [];
336
337
        $flip = array_flip($columns);
338
        foreach ($result as $key => $value) {
339
            $content = self::value($object, $key, $type, false);
340
            if ($content !== $value) {
341
                $data[$key] = $content;
342
            }
343
            if (!$id && $content === null) {
344
                unset($data[$key]);
345
            }
346
        }
347
348
        if ($data) {
349
            $sql = '
350
                UPDATE
351
                    '.$tableName.'
352
                SET
353
354
            ';
355
            foreach ($data as $key => $value) {
356
                $meta = self::$metadata[$tableName]->getFieldMapping($flip[$key])['type'];
357
                if (in_array($meta, [
358
                    'boolean',
359
                    'integer',
360
                    'longint',
361
                ])) {
362
                    $value = intval($value);
363
                } else {
364
                    $value = "'".addslashes(trim($value))."'";
365
                }
366
                $sql .= " ".$key." = ".$value.",";
367
            }
368
            $sql = substr($sql, 0, -1).' WHERE id = '.$id;
369
370
            self::runSQL($sql);
371
        }
372
    }
373
374 View Code Duplication
    public static function delete($object, $where = [], $noFkCheck = false, $manager = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
375
    {
376
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
377
378
        $sql = 'DELETE FROM '.$tableName.self::buildWhere($tableName, $where);
379
        self::runSQL($sql);
380
    }
381
382 View Code Duplication
    public static function link($object, $data, $noFkCheck = false, $manager = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
383
    {
384
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
385
386
        $data['table_name'] = $tableName;
387
        self::persist($data, true, [], $noFkCheck, $manager);
388
    }
389
}
390