Completed
Push — master ( 475860...2973a7 )
by CodexShaper
04:33
created

DatabaseController   F

Complexity

Total Complexity 76

Size/Duplication

Total Lines 572
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 337
c 1
b 0
f 0
dl 0
loc 572
ccs 0
cts 455
cp 0
rs 2.32
wmc 76

15 Methods

Rating   Name   Duplication   Size   Complexity  
A getTableColumns() 0 15 3
A index() 0 3 1
A all() 0 38 5
B create() 0 45 6
B getTable() 0 46 8
A saveTemplate() 0 34 4
A getInputType() 0 9 3
A getUniqueId() 0 5 2
B update() 0 48 7
C updateCrudFields() 0 78 11
A updateTemplates() 0 19 5
A removeTemplate() 0 11 3
B updateMongoDbTable() 0 56 9
B inputTypes() 0 76 1
B delete() 0 42 8

How to fix   Complexity   

Complex Class

Complex classes like DatabaseController 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 DatabaseController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace CodexShaper\DBM\Http\Controllers;
4
5
use CodexShaper\DBM\Database\Schema\Table;
6
use CodexShaper\DBM\Facades\Driver;
7
use CodexShaper\DBM\Models\CollectionField;
8
use CodexShaper\DBM\Models\DBM_Collection;
9
use DBM;
0 ignored issues
show
Bug introduced by
The type DBM was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Illuminate\Http\Request;
11
use Illuminate\Support\Str;
12
13
class DatabaseController extends Controller
14
{
15
16
    public function index()
17
    {
18
        return view('dbm::app');
19
    }
20
21
    public function all(Request $request)
22
    {
23
        // return response()->json(['success' => false, 'data' => escapeshellarg($request->perPage)]);
24
        if ($request->ajax()) {
25
26
            if (($response = DBM::authorize('database.browse')) !== true) {
27
                return $response;
28
            }
29
30
            try
31
            {
32
                $perPage         = (int) $request->perPage;
33
                $query           = $request->q;
34
                $tables          = Table::paginate($perPage, null, [], $query);
35
                $userPermissions = DBM::userPermissions();
36
37
                $newTables = [];
38
39
                foreach ($tables as $table) {
40
41
                    $newTables[] = $table;
42
                }
43
44
                return response()->json([
45
                    'success'         => true,
46
                    'tables'          => $newTables,
47
                    'pagination'      => $tables,
48
                    'userPermissions' => $userPermissions,
49
                ]);
50
51
            } catch (\Exception $e) {
52
                return response()->json([
53
                    'success' => false,
54
                    'errors'  => [$e->getMessage()],
55
                ], 400);
56
            }
57
        }
58
        return response()->json(['success' => false]);
59
    }
60
61
    public function getTable(Request $request)
62
    {
63
        if ($request->ajax()) {
64
65
            if (($response = DBM::authorize('database.update')) !== true) {
66
                return $response;
67
            }
68
69
            $userPermissions = DBM::userPermissions();
70
            $table           = Table::getTable($request->name);
71
            $object          = DBM::Object()->where('name', $request->name)->first();
72
            $isCrudExists    = false;
73
            $columns         = $table['columns'];
74
            $newColumns      = [];
75
76
            if ($object) {
77
                $fields = $object->fields()->orderBy('order', 'ASC')->get();
78
                if (count($fields) > 0) {
79
                    foreach ($fields as $field) {
80
                        foreach ($columns as $key => $column) {
81
                            if ($field->name == $column->name) {
82
                                // $column->id    = $field->id;
83
                                $column->order = $field->order;
84
                                $newColumns[]  = $column;
85
                                unset($columns[$key]);
86
                                $columns = array_values($columns);
87
                            }
88
                        }
89
                    }
90
91
                    $table['columns'] = $newColumns;
92
                    // $columns          = $newColumns;
93
                    $isCrudExists = true;
94
                }
95
            }
96
97
            return response()->json([
98
                'success'         => true,
99
                'table'           => $table,
100
                'isCrudExists'    => $isCrudExists,
101
                'userPermissions' => $userPermissions,
102
                'templates'       => DBM::templates(),
103
            ]);
104
        }
105
106
        return response()->json(['success' => false]);
107
    }
108
109
    public function getTableColumns(Request $request)
110
    {
111
        if ($request->ajax()) {
112
113
            if (($response = DBM::authorize('crud.update')) !== true) {
114
                return $response;
115
            }
116
117
            $table  = Table::getTable($request->table);
118
            $fields = $table['columns'];
119
120
            return response()->json(['success' => true, 'fields' => $fields]);
121
        }
122
123
        return response()->json(['success' => false]);
124
    }
125
126
    public function create(Request $request)
127
    {
128
        if ($request->ajax()) {
129
130
            $table = json_decode($request->table, true);
131
132
            if (($response = DBM::authorize('database.create')) !== true) {
133
                return $response;
134
            }
135
136
            try
137
            {
138
                Table::create($request->table);
139
140
                if (Driver::isMongoDB()) {
141
                    $collection           = new DBM_Collection;
142
                    $collection->name     = $table['name'];
143
                    $collection->old_name = $table['name'];
144
                    $collection->extra    = [];
145
146
                    if ($collection->save()) {
147
                        $id = $collection->_id;
148
149
                        $collection_field = new CollectionField;
150
151
                        $collection_field->dbm_collection_id = $id;
152
                        $collection_field->name              = '_id';
153
                        $collection_field->old_name          = '_id';
154
                        $collection_field->type              = 'ObjectId';
155
                        $collection_field->index             = 'PRIMARY_KEY';
156
                        $collection_field->extra             = [];
157
158
                        $collection_field->save();
159
                    }
160
                }
161
                return response()->json(['success' => true]);
162
            } catch (\Exception $e) {
163
                return response()->json([
164
                    'success' => false,
165
                    'errors'  => [$e->getMessage()],
166
                ], 400);
167
            }
168
        }
169
170
        return response()->json(['success' => false]);
171
    }
172
173
    public function updateTemplates($templates)
174
    {
175
        if (is_array($templates) && count($templates) > 0) {
176
177
            foreach ($templates as $field) {
178
179
                if ($template = DBM::Template()->where('old_name', $field['oldName'])->first()) {
180
181
                    $template->name           = $field['name'];
182
                    $template->old_name       = $field['name'];
183
                    $template->type           = $field['type']['name'];
184
                    $template->length         = $field['length'];
185
                    $template->index          = $field['index'];
186
                    $template->default        = $field['default'];
187
                    $template->notnull        = $field['notnull'];
188
                    $template->unsigned       = $field['unsigned'];
189
                    $template->auto_increment = $field['autoincrement'];
190
191
                    $template->update();
192
                }
193
            }
194
        }
195
    }
196
197
    public function updateMongoDbTable($table)
198
    {
199
        $tableName = $table['oldName'];
200
        $newName   = $table['name'];
201
        $columns   = $table['columns'];
202
203
        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
204
            if ($tableName != $newName) {
205
                $collection->name     = $newName;
206
                $collection->old_name = $newName;
207
                $collection->update();
208
            }
209
        } else {
210
            $collection           = new DBM_Collection;
211
            $collection->name     = $newName;
212
            $collection->old_name = $newName;
213
            $collection->save();
214
        }
215
216
        if ($collection) {
217
218
            $id         = $collection->_id;
219
            $fieldNames = (!empty($collection->fields)) ? $collection->fields->pluck('old_name')->toArray() : [];
220
221
            foreach ($columns as $column) {
222
223
                if (in_array($column['oldName'], $fieldNames)) {
224
225
                    $collection_field = CollectionField::where('old_name', $column['oldName'])->first();
226
227
                    $collection_field->name     = $column['name'];
228
                    $collection_field->old_name = $column['oldName'];
229
                    $collection_field->type     = $column['type']['name'];
230
                    $collection_field->update();
231
                    $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
232
                } else {
233
234
                    $collection_field = new CollectionField;
235
236
                    $collection_field->dbm_collection_id = $id;
237
                    $collection_field->name              = $column['name'];
238
                    $collection_field->old_name          = $column['name'];
239
                    $collection_field->type              = $column['type']['name'];
240
                    $collection_field->index             = '';
241
                    $collection_field->extra             = [];
242
243
                    $collection_field->save();
244
                }
245
            }
246
247
            if (count($fieldNames) > 0) {
248
                foreach ($fieldNames as $fieldName) {
249
                    $field = CollectionField::where([
250
                        'dbm_collection_id' => $id,
251
                        'name'              => $fieldName])->first();
252
                    $field->delete();
253
                }
254
            }
255
256
        }
257
    }
258
259
    public function updateCrudFields($table)
260
    {
261
        $tableName = $table['oldName'];
262
        $newName   = $table['name'];
263
        $columns   = $table['columns'];
264
265
        if ($tableName != $newName) {
266
267
            DBM::Object()->where('slug', Str::slug($tableName))->update([
268
                'name'         => $newName,
269
                'slug'         => Str::slug($newName),
270
                'display_name' => ucfirst($newName),
271
            ]);
272
273
            $tableName = $newName;
274
        }
275
276
        if ($object = DBM::Object()::where('slug', Str::slug($tableName))->first()) {
277
278
            $fieldNames = $object->fields->pluck('name')->toArray();
279
            // $relationshipItems = [];
280
281
            foreach ($columns as $column) {
282
283
                $columnType = $column['type'];
284
285
                if (in_array($column['oldName'], $fieldNames)) {
286
287
                    $field = DBM::Field()->where([
288
                        'dbm_object_id' => $object->id,
289
                        'name'          => $column['oldName'],
290
                    ])->first();
291
292
                    $field->name = $column['name'];
293
                    if ($column['oldName'] != $column['name']) {
294
                        $field->display_name = ucfirst($column['name']);
295
                    }
296
                    $field->order = $column['order'];
297
                    $field->update();
298
299
                    $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
300
                } else {
301
302
                    if (DBM::Field()->where([
303
                        'dbm_object_id' => $object->id,
304
                        'name'          => $column['name']])->first()) {
305
                        return response()->json([
306
                            'success' => false,
307
                            'errors'  => ["Field name must be unique. " . $column['name'] . " are duplicate"],
308
                        ], 400);
309
                    }
310
311
                    $field                = DBM::Field();
312
                    $field->dbm_object_id = $object->id;
313
                    $field->name          = $column['name'];
314
                    $field->display_name  = ucfirst($column['name']);
315
                    $field->type          = static::getInputType($columnType['name']);
316
                    $field->order         = $column['order'];
317
318
                    if ($column['autoincrement'] == true) {
319
                        $field->create = false;
320
                        $field->read   = false;
321
                        $field->edit   = false;
322
                        $field->delete = false;
323
                    }
324
325
                    $field->save();
326
                }
327
328
            }
329
330
            if (count($fieldNames) > 0) {
331
                foreach ($fieldNames as $fieldName) {
332
                    $field = DBM::Field()->where([
333
                        'dbm_object_id' => $object->id,
334
                        'name'          => $fieldName])->first();
335
                    if ($field->type != 'relationship') {
336
                        $field->delete();
337
                    }
338
                }
339
            }
340
        }
341
    }
342
343
    public function update(Request $request)
344
    {
345
        if ($request->ajax()) {
346
347
            if (($response = DBM::authorize('database.update')) !== true) {
348
                return $response;
349
            }
350
351
            $table = $request->table;
352
353
            if (!is_array($table)) {
354
                $table = json_decode($table, true);
355
            }
356
357
            $tableName = $table['oldName'];
358
            $newName   = $table['name'];
0 ignored issues
show
Unused Code introduced by
The assignment to $newName is dead and can be removed.
Loading history...
359
360
            try
361
            {
362
                // Update Template
363
                $this->updateTemplates($request->templates);
364
365
                if (Table::exists($tableName)) {
366
367
                    if (Driver::isMongoDB()) {
368
369
                        $this->updateMongoDbTable($table);
370
                    }
371
372
                    // Update Database
373
                    Table::update($request->table);
374
375
                    // Update Crud fields
376
                    $this->updateCrudFields($table);
377
378
                    return response()->json(['success' => true]);
379
                }
380
381
            } catch (\Exception $e) {
382
383
                return response()->json([
384
                    'success' => false,
385
                    'errors'  => [$e->getMessage()],
386
                ], 400);
387
            }
388
        }
389
390
        return response()->json(['success' => false]);
391
392
    }
393
394
    public function delete(Request $request)
395
    {
396
        if ($request->ajax()) {
397
398
            if (($response = DBM::authorize('database.delete')) !== true) {
399
                return $response;
400
            }
401
402
            $tableName = $request->table;
403
404
            try
405
            {
406
                if (Table::exists($tableName)) {
407
408
                    if (Driver::isMongoDB()) {
409
                        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
410
                            $collection->fields()->delete();
411
                            $collection->delete();
412
                        }
413
                    }
414
415
                    if ($object = DBM::Object()->where('slug', Str::slug($tableName))->first()) {
416
417
                        $object->fields()->delete();
418
                        $object->delete();
419
                    }
420
421
                    Table::drop($tableName);
422
423
                    return response()->json(['success' => true]);
424
                }
425
426
            } catch (\Exception $e) {
427
428
                return response()->json([
429
                    'success' => false,
430
                    'errors'  => [$e->getMessage()],
431
                ], 400);
432
            }
433
        }
434
435
        return response()->json(['success' => false]);
436
    }
437
438
    public static function getInputType($name)
439
    {
440
        $types = static::inputTypes();
441
        foreach ($types as $type => $value) {
442
            if (in_array($name, $value)) {
443
                return $type;
444
            }
445
        }
446
        return 'text';
447
    }
448
449
    public static function inputTypes()
450
    {
451
        return [
452
            'number'    => [
453
                'tinyint',
454
                'smallint',
455
                'mediumint',
456
                'integer',
457
                'int',
458
                'bigint',
459
                'decimal',
460
                'numeric',
461
            ],
462
            'text'      => [
463
                'money',
464
                'float',
465
                'real',
466
                'double',
467
                'double precision',
468
                // String
469
                'char',
470
                'character',
471
                'varchar',
472
                'character varying',
473
                'string',
474
                'guid',
475
                'uuid',
476
                // Lists
477
                'json',
478
                'jsonb',
479
                'json_array',
480
            ],
481
            'password'  => [
482
                'password',
483
            ],
484
            'email'     => [],
485
            'select'    => [],
486
            'radio'     => [],
487
            'checkbox'  => [
488
                'boolean',
489
            ],
490
            'textarea'  => [
491
                'tinytext',
492
                'text',
493
                'mediumtext',
494
                'longtext',
495
                'tsquery',
496
                'tsvector',
497
                'xml',
498
            ],
499
            'date'      => [
500
                'date',
501
                'datetime',
502
                'year',
503
                'timetz',
504
                'timestamptz',
505
                'datetimetz',
506
                'dateinterval',
507
                'interval',
508
            ],
509
            'timestamp' => [
510
                'timestamp',
511
            ],
512
            'color'     => [],
513
            'file'      => [],
514
            'image'     => [],
515
            'hidden'    => [],
516
            'month'     => [],
517
            'week'      => [],
518
            'time'      => [
519
                'time',
520
            ],
521
            'url'       => [],
522
            'tel'       => [],
523
            'submit'    => [],
524
            'search'    => [],
525
        ];
526
    }
527
528
    /*
529
     * Store Template
530
     */
531
    public function saveTemplate(Request $request)
532
    {
533
        $field = $request->template;
534
        try
535
        {
536
            if (DBM::Template()->where('name', $field['name'])->first()) {
537
                return response()->json([
538
                    'success' => false,
539
                    'errors'  => [" The template name must be unique. " . $field['name'] . " already exist."],
540
                ], 400);
541
            }
542
543
            $template                 = DBM::Template();
544
            $template->name           = $field['name'];
545
            $template->old_name       = $field['name'];
546
            $template->type           = $field['type']['name'];
547
            $template->length         = $field['length'];
548
            $template->index          = $field['index'];
549
            $template->default        = $field['default'];
550
            $template->notnull        = $field['notnull'];
551
            $template->unsigned       = $field['unsigned'];
552
            $template->auto_increment = $field['autoincrement'];
553
554
            if ($template->save()) {
555
                return response()->json(['success' => true, 'templates' => DBM::templates()]);
556
            }
557
558
        } catch (\Exception $e) {
559
            return response()->json([
560
                'success' => false,
561
                'errors'  => [$e->getMessage()],
562
            ], 400);
563
        }
564
        return response()->json(['success' => true, 'template' => $request->all()]);
565
    }
566
567
    public function removeTemplate(Request $request)
568
    {
569
        if ($template = DBM::Template()->where('name', $request->name)->first()) {
570
            if ($template->delete()) {
571
                return response()->json(['success' => true, 'templates' => DBM::templates()]);
572
            }
573
        }
574
        return response()->json([
575
            'success' => false,
576
            'errors'  => ['The template '+$request->name . " not found"],
577
        ], 400);
578
    }
579
580
    public function getUniqueId()
581
    {
582
        $id = new \MongoDB\BSON\ObjectId();
583
        foreach ($id as $key => $value) {
584
            return response()->json(['success' => true, 'id' => $value]);
585
        }
586
    }
587
588
}
589