Passed
Push — master ( 0ed784...b28e07 )
by CodexShaper
14:16
created

DatabaseController::create()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 45
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 28
c 1
b 0
f 0
nc 16
nop 1
dl 0
loc 45
rs 8.8497
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');
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

18
        return /** @scrutinizer ignore-call */ view('dbm::app');
Loading history...
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([
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

44
                return /** @scrutinizer ignore-call */ response()->json([
Loading history...
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;
0 ignored issues
show
Unused Code introduced by
The assignment to $columns is dead and can be removed.
Loading history...
93
                    $isCrudExists     = true;
94
                }
95
            }
96
97
            return response()->json([
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

97
            return /** @scrutinizer ignore-call */ response()->json([
Loading history...
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]);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

120
            return /** @scrutinizer ignore-call */ response()->json(['success' => true, 'fields' => $fields]);
Loading history...
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()) {
0 ignored issues
show
Bug introduced by
The method isMongoDB() does not exist on CodexShaper\DBM\Facades\Driver. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

140
                if (Driver::/** @scrutinizer ignore-call */ isMongoDB()) {
Loading history...
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]);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

161
                return /** @scrutinizer ignore-call */ response()->json(['success' => true]);
Loading history...
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 createObject($table)
174
    {
175
        if (($response = DBM::isLoggedIn()) !== true) {
176
            return $response;
177
        }
178
179
        if (($response = DBM::authorize('database.create')) !== true) {
180
            return $response;
181
        }
182
183
        if (!is_array($table)) {
184
            $table = json_decode($table, true);
185
        }
186
187
        $tableName = $table['name'];
188
        $columns   = $table['columns'];
189
190
        $object               = DBM::Object();
191
        $object->name         = $tableName;
192
        $object->slug         = Str::slug($tableName);
193
        $object->display_name = ucfirst($tableName);
194
        if ($object->save()) {
195
            foreach ($columns as $column) {
196
                $columnType = $column['type'];
197
198
                $field                = DBM::Field();
199
                $field->dbm_object_id = $object->id;
200
                $field->name          = $column['name'];
201
                $field->display_name  = strtoupper($column['name']);
202
                $field->type          = static::getInputType($columnType['name']);
203
                $field->required      = true;
204
                $field->create        = false;
205
                $field->read          = false;
206
                $field->edit          = false;
207
                $field->delete        = false;
208
                $field->order         = $column['order'];
209
                $field->save();
210
            }
211
212
            return true;
213
        }
214
215
        return false;
216
217
    }
218
219
    public function update(Request $request)
220
    {
221
        if ($request->ajax()) {
222
223
            if (($response = DBM::authorize('database.update')) !== true) {
224
                return $response;
225
            }
226
227
            if (!is_array($request->table)) {
228
                $table = json_decode($request->table, true);
229
            }
230
231
            $tableName = $table['oldName'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $table does not seem to be defined for all execution paths leading up to this point.
Loading history...
232
            $newName   = $table['name'];
233
            $columns   = $table['columns'];
234
235
            try
236
            {
237
                // Update Template
238
                if (is_array($request->templates) && count($request->templates) > 0) {
239
240
                    foreach ($request->templates as $field) {
241
242
                        if ($template = DBM::Template()->where('old_name', $field['oldName'])->first()) {
243
244
                            $template->name           = $field['name'];
245
                            $template->old_name       = $field['name'];
246
                            $template->type           = $field['type']['name'];
247
                            $template->length         = $field['length'];
248
                            $template->index          = $field['index'];
249
                            $template->default        = $field['default'];
250
                            $template->notnull        = $field['notnull'];
251
                            $template->unsigned       = $field['unsigned'];
252
                            $template->auto_increment = $field['autoincrement'];
253
254
                            $template->update();
255
                        }
256
                    }
257
                }
258
259
                if (Table::exists($tableName)) {
260
261
                    if (Driver::isMongoDB()) {
262
263
                        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
264
                            if ($tableName != $newName) {
265
                                $collection->name     = $newName;
266
                                $collection->old_name = $newName;
267
                                $collection->update();
268
                            }
269
                        } else {
270
                            $collection           = new DBM_Collection;
271
                            $collection->name     = $newName;
272
                            $collection->old_name = $newName;
273
                            $collection->save();
274
                        }
275
276
                        if ($collection) {
277
278
                            $id         = $collection->_id;
279
                            $fieldNames = (!empty($collection->fields)) ? $collection->fields->pluck('old_name')->toArray() : [];
280
281
                            foreach ($columns as $column) {
282
283
                                if (in_array($column['oldName'], $fieldNames)) {
284
285
                                    $collection_field = CollectionField::where('old_name', $column['oldName'])->first();
286
287
                                    $collection_field->name     = $column['name'];
288
                                    $collection_field->old_name = $column['oldName'];
289
                                    $collection_field->type     = $column['type']['name'];
290
                                    $collection_field->update();
291
                                    $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
292
                                } else {
293
294
                                    $collection_field = new CollectionField;
295
296
                                    $collection_field->dbm_collection_id = $id;
297
                                    $collection_field->name              = $column['name'];
298
                                    $collection_field->old_name          = $column['name'];
299
                                    $collection_field->type              = $column['type']['name'];
300
                                    $collection_field->index             = '';
301
                                    $collection_field->extra             = [];
302
303
                                    $collection_field->save();
304
                                }
305
                            }
306
307
                            if (count($fieldNames) > 0) {
308
                                foreach ($fieldNames as $fieldName) {
309
                                    $field = CollectionField::where([
310
                                        'dbm_collection_id' => $id,
311
                                        'name'              => $fieldName])->first();
312
                                    $field->delete();
313
                                }
314
                            }
315
316
                        }
317
                    }
318
319
                    // Update Database
320
                    Table::update($request->table);
321
322
                    // Update Crud fields
323
                    if ($tableName != $newName) {
324
325
                        DBM::Object()->where('slug', Str::slug($tableName))->update([
326
                            'name'         => $newName,
327
                            'slug'         => Str::slug($newName),
328
                            'display_name' => ucfirst($newName),
329
                        ]);
330
331
                        $tableName = $newName;
332
                    }
333
334
                    if ($object = DBM::Object()::where('slug', Str::slug($tableName))->first()) {
335
336
                        $fieldNames        = $object->fields->pluck('name')->toArray();
337
                        $relationshipItems = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $relationshipItems is dead and can be removed.
Loading history...
338
339
                        foreach ($columns as $column) {
340
341
                            $columnType = $column['type'];
342
343
                            if (in_array($column['oldName'], $fieldNames)) {
344
345
                                $field = DBM::Field()->where([
346
                                    'dbm_object_id' => $object->id,
347
                                    'name'          => $column['oldName'],
348
                                ])->first();
349
350
                                $field->name = $column['name'];
351
                                if ($column['oldName'] != $column['name']) {
352
                                    $field->display_name = ucfirst($column['name']);
353
                                }
354
                                $field->order = $column['order'];
355
                                $field->update();
356
357
                                $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
358
                            } else {
359
360
                                if (DBM::Field()->where([
361
                                    'dbm_object_id' => $object->id,
362
                                    'name'          => $column['name']])->first()) {
363
                                    return response()->json([
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

363
                                    return /** @scrutinizer ignore-call */ response()->json([
Loading history...
364
                                        'success' => false,
365
                                        'errors'  => ["Field name must be unique. " . $column['name'] . " are duplicate"],
366
                                    ], 400);
367
                                }
368
369
                                $field                = DBM::Field();
370
                                $field->dbm_object_id = $object->id;
371
                                $field->name          = $column['name'];
372
                                $field->display_name  = ucfirst($column['name']);
373
                                $field->type          = static::getInputType($columnType['name']);
374
                                $field->order         = $column['order'];
375
376
                                if ($column['autoincrement'] == true) {
377
                                    $field->create = false;
378
                                    $field->read   = false;
379
                                    $field->edit   = false;
380
                                    $field->delete = false;
381
                                }
382
383
                                $field->save();
384
                            }
385
386
                        }
387
388
                        if (count($fieldNames) > 0) {
389
                            foreach ($fieldNames as $fieldName) {
390
                                $field = DBM::Field()->where([
391
                                    'dbm_object_id' => $object->id,
392
                                    'name'          => $fieldName])->first();
393
                                if ($field->type != 'relationship') {
394
                                    $field->delete();
395
                                }
396
                            }
397
                        }
398
                    }
399
400
                    return response()->json(['success' => true]);
401
                }
402
403
            } catch (\Exception $e) {
404
405
                return response()->json([
406
                    'success' => false,
407
                    'errors'  => [$e->getMessage()],
408
                ], 400);
409
            }
410
        }
411
412
        return response()->json(['success' => false]);
413
414
    }
415
416
    public function delete(Request $request)
417
    {
418
        if ($request->ajax()) {
419
420
            if (($response = DBM::authorize('database.delete')) !== true) {
421
                return $response;
422
            }
423
424
            $tableName = $request->table;
425
426
            try
427
            {
428
                if (Table::exists($tableName)) {
429
430
                    if (Driver::isMongoDB()) {
431
                        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
432
                            $collection->fields()->delete();
433
                            $collection->delete();
434
                        }
435
                    }
436
437
                    if ($object = DBM::Object()->where('slug', Str::slug($tableName))->first()) {
438
439
                        $object->fields()->delete();
440
                        $object->delete();
441
                    }
442
443
                    Table::drop($tableName);
444
445
                    return response()->json(['success' => true]);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

445
                    return /** @scrutinizer ignore-call */ response()->json(['success' => true]);
Loading history...
446
                }
447
448
            } catch (\Exception $e) {
449
450
                return response()->json([
451
                    'success' => false,
452
                    'errors'  => [$e->getMessage()],
453
                ], 400);
454
            }
455
        }
456
457
        return response()->json(['success' => false]);
458
    }
459
460
    public static function getInputType($name)
461
    {
462
        $types = static::inputTypes();
463
        foreach ($types as $type => $value) {
464
            if (in_array($name, $value)) {
465
                return $type;
466
            }
467
        }
468
        return 'text';
469
    }
470
471
    public static function inputTypes()
472
    {
473
        return [
474
            'number'    => [
475
                'tinyint',
476
                'smallint',
477
                'mediumint',
478
                'integer',
479
                'int',
480
                'bigint',
481
                'decimal',
482
                'numeric',
483
            ],
484
            'text'      => [
485
                'money',
486
                'float',
487
                'real',
488
                'double',
489
                'double precision',
490
                // String
491
                'char',
492
                'character',
493
                'varchar',
494
                'character varying',
495
                'string',
496
                'guid',
497
                'uuid',
498
                // Lists
499
                'json',
500
                'jsonb',
501
                'json_array',
502
            ],
503
            'password'  => [
504
                'password',
505
            ],
506
            'email'     => [],
507
            'select'    => [],
508
            'radio'     => [],
509
            'checkbox'  => [
510
                'boolean',
511
            ],
512
            'textarea'  => [
513
                'tinytext',
514
                'text',
515
                'mediumtext',
516
                'longtext',
517
                'tsquery',
518
                'tsvector',
519
                'xml',
520
            ],
521
            'date'      => [
522
                'date',
523
                'datetime',
524
                'year',
525
                'timetz',
526
                'timestamptz',
527
                'datetimetz',
528
                'dateinterval',
529
                'interval',
530
            ],
531
            'timestamp' => [
532
                'timestamp',
533
            ],
534
            'color'     => [],
535
            'file'      => [],
536
            'image'     => [],
537
            'hidden'    => [],
538
            'month'     => [],
539
            'week'      => [],
540
            'time'      => [
541
                'time',
542
            ],
543
            'url'       => [],
544
            'tel'       => [],
545
            'submit'    => [],
546
            'search'    => [],
547
        ];
548
    }
549
550
    /*
551
     * Store Template
552
     */
553
    public function saveTemplate(Request $request)
554
    {
555
        $field = $request->template;
556
        try
557
        {
558
            if (DBM::Template()->where('name', $field['name'])->first()) {
559
                return response()->json([
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

559
                return /** @scrutinizer ignore-call */ response()->json([
Loading history...
560
                    'success' => false,
561
                    'errors'  => [" The template name must be unique. " . $field['name'] . " already exist."],
562
                ], 400);
563
            }
564
565
            $template                 = DBM::Template();
566
            $template->name           = $field['name'];
567
            $template->old_name       = $field['name'];
568
            $template->type           = $field['type']['name'];
569
            $template->length         = $field['length'];
570
            $template->index          = $field['index'];
571
            $template->default        = $field['default'];
572
            $template->notnull        = $field['notnull'];
573
            $template->unsigned       = $field['unsigned'];
574
            $template->auto_increment = $field['autoincrement'];
575
576
            if ($template->save()) {
577
                return response()->json(['success' => true, 'templates' => DBM::templates()]);
578
            }
579
580
        } catch (\Exception $e) {
581
            return response()->json([
582
                'success' => false,
583
                'errors'  => [$e->getMessage()],
584
            ], 400);
585
        }
586
        return response()->json(['success' => true, 'template' => $request->all()]);
587
    }
588
589
    public function removeTemplate(Request $request)
590
    {
591
        if ($template = DBM::Template()->where('name', $request->name)->first()) {
592
            if ($template->delete()) {
593
                return response()->json(['success' => true, 'templates' => DBM::templates()]);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

593
                return /** @scrutinizer ignore-call */ response()->json(['success' => true, 'templates' => DBM::templates()]);
Loading history...
594
            }
595
        }
596
        return response()->json([
597
            'success' => false,
598
            'errors'  => ['The template '+$request->name . " not found"],
599
        ], 400);
600
    }
601
602
    public function getUniqueId()
603
    {
604
        $id = new \MongoDB\BSON\ObjectId();
605
        foreach ($id as $key => $value) {
606
            return response()->json(['success' => true, 'id' => $value]);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

606
            return /** @scrutinizer ignore-call */ response()->json(['success' => true, 'id' => $value]);
Loading history...
607
        }
608
    }
609
610
}
611