Passed
Branch master (c65ffc)
by Dāvis
03:08
created

QuickInsertRepository   F

Complexity

Total Complexity 89

Size/Duplication

Total Lines 388
Duplicated Lines 4.9 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 19
loc 388
rs 1.5789
wmc 89

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
A runSQL() 0 10 2
A findNextIdExt() 0 6 1
A findNextId() 0 12 2
A getTable() 0 13 4
C buildWhere() 0 24 10
B value() 0 23 5
B variable() 0 10 5
C update() 3 47 10
A link() 6 6 1
C persist() 3 48 12
C get() 0 29 11
A delete() 6 6 1

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) ?: null;
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][$field];
232
                }
233
            } elseif ($one) {
234
                $result = $result[0];
235
            }
236
        }
237
238
        return $result;
239
    }
240
241
    private static function variable(&$value)
242
    {
243
        if ($value instanceof \DateTime) {
244
            $value = "'".addslashes(trim($value->format('Y-m-d H:i:s')))."'";
245
        } elseif (!is_numeric($value)) {
246
            $value = "'".addslashes(trim($value))."'";
247
        }
248
249
        if (trim($value) === '' || trim($value) === "''") {
250
            $value = null;
251
        }
252
    }
253
254
    private static function value($object, $variable, $type, $check = true)
255
    {
256
        $value = null;
257
        if ($type === 'object') {
258
259
            $variables = explode('_', $variable);
260
            foreach ($variables as &$var) {
261
                $var = ucfirst($var);
262
            }
263
            $variable = implode('', $variables);
264
265
            $value = $object->{'get'.ucfirst($variable)}();
266
        } else {
267
            if (isset($object[$variable])) {
268
                $value = $object[$variable];
269
            }
270
        }
271
272
        if ($check) {
273
            self::variable($value);
274
        }
275
276
        return $value;
277
    }
278
279
    public static function persist($object, $full = false, $extraFields = [], $noFkCheck = false, $manager = null)
280
    {
281
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
282
283
        $id = self::findNextId($tableName);
284
        $data = [];
285
286 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...
287
            $columns = array_merge($columns, $extraFields[$tableName]);
288
        }
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);
332
333
        $result = self::get(['table_name' => $tableName], true, ['id' => $id], true, ['*']);
334
        unset($result['id']);
335
336
        $data = [];
337
338 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...
339
            $columns = array_merge($columns, $extraFields[$tableName]);
340
        }
341
342
        $flip = array_flip($columns);
343
        foreach ($result as $key => $value) {
344
            $content = self::value($object, $key, $type, false);
345
            if ($content !== $value) {
346
                $data[$key] = $content;
347
            }
348
            if (!$id && $content === null) {
349
                unset($data[$key]);
350
            }
351
        }
352
353
        if ($data) {
354
            $sql = '
355
                UPDATE
356
                    '.$tableName.'
357
                SET
358
359
            ';
360
            foreach ($data as $key => $value) {
361
                $meta = self::$metadata[$tableName]->getFieldMapping($flip[$key])['type'];
362
                if (in_array($meta, [
363
                    'boolean',
364
                    'integer',
365
                    'longint',
366
                ])) {
367
                    $value = intval($value);
368
                } else {
369
                    $value = "'".addslashes(trim($value))."'";
370
                }
371
                $sql .= " ".$key." = ".$value.",";
372
            }
373
            $sql = substr($sql, 0, -1).' WHERE id = '.$id;
374
375
            self::runSQL($sql);
376
        }
377
    }
378
379 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...
380
    {
381
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
382
383
        $sql = 'DELETE FROM '.$tableName.self::buildWhere($tableName, $where);
384
        self::runSQL($sql);
385
    }
386
387 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...
388
    {
389
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
390
391
        $data['table_name'] = $tableName;
392
        self::persist($data, true, [], $noFkCheck, $manager);
393
    }
394
}
395