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

QuickInsertRepository::variable()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 6
c 0
b 0
f 0
nc 6
nop 1
dl 0
loc 10
rs 8.8571
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][$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
            $variable = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $variable is dead and can be removed.
Loading history...
293
            if (!is_array($key) && !is_array($value)) {
294
                $value = self::value($object, $value, $type);
295
                if ($value !== null) {
296
                    $data[$key] = $value;
297
                    if ($key === 'id') {
298
                        $idd = $value;
299
                    }
300
                }
301
            }
302
        }
303
304
        $sql = null;
305
        if (!$full) {
306
            $data['id'] = $id;
307
        } else {
308
            $id = $idd;
309
        }
310
311
        if (!self::isEmpty($data)) {
312
            $sql = '
313
                INSERT INTO
314
                    '.$tableName.'
315
                        ('.implode(',', array_keys($data)).')
316
                VALUES
317
                    ('.implode(',', array_values($data)).')
318
            ';
319
        } else {
320
            $id = null;
321
        }
322
323
        if ($sql !== null && $id !== null) {
324
            self::runSQL($sql);
325
        }
326
327
        return $id;
328
    }
329
330
    public static function update($id, $object, $extraFields = [], $noFkCheck = false, $manager = null)
331
    {
332
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
333
334
        $result = self::get(['table_name' => $tableName], true, ['id' => $id], true, ['*']);
335
        unset($result['id']);
336
337
        $data = [];
338
339 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...
340
            $columns = array_merge($columns, $extraFields[$tableName]);
341
        }
342
343
        $flip = array_flip($columns);
344
        foreach ($result as $key => $value) {
345
            $content = self::value($object, $key, $type, false);
346
            if ($content !== $value) {
347
                $data[$key] = $content;
348
            }
349
            if (!$id && $content === null) {
350
                unset($data[$key]);
351
            }
352
        }
353
354
        if ($data) {
355
            $sql = '
356
                UPDATE
357
                    '.$tableName.'
358
                SET
359
360
            ';
361
            foreach ($data as $key => $value) {
362
                $meta = self::$metadata[$tableName]->getFieldMapping($flip[$key])['type'];
363
                if (in_array($meta, [
364
                    'boolean',
365
                    'integer',
366
                    'longint',
367
                ])) {
368
                    $value = intval($value);
369
                } else {
370
                    $value = "'".addslashes(trim($value))."'";
371
                }
372
                $sql .= " ".$key." = ".$value.",";
373
            }
374
            $sql = substr($sql, 0, -1).' WHERE id = '.$id;
375
376
            self::runSQL($sql);
377
        }
378
    }
379
380 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...
381
    {
382
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
383
384
        $sql = 'DELETE FROM '.$tableName.self::buildWhere($tableName, $where);
385
        self::runSQL($sql);
386
    }
387
388 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...
389
    {
390
        self::getTable($object, $tableName, $columns, $type, $noFkCheck, $manager);
391
392
        $data['table_name'] = $tableName;
393
        self::persist($data, true, [], $noFkCheck, $manager);
394
    }
395
}
396