Completed
Push — master ( 5af970...ffb252 )
by CodexShaper
04:49
created

DatabaseController::updateTemplates()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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