Completed
Push — master ( 24dcac...1d88b8 )
by CodexShaper
04:29
created

CrudController::storeOrUpdate()   B

Complexity

Conditions 10
Paths 16

Size

Total Lines 47
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
eloc 23
c 2
b 0
f 0
nc 16
nop 1
dl 0
loc 47
ccs 0
cts 33
cp 0
crap 110
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace CodexShaper\DBM\Http\Controllers;
4
5
use CodexShaper\DBM\Database\Drivers\MongoDB\Type;
6
use CodexShaper\DBM\Database\Schema\Table;
7
use CodexShaper\DBM\Facades\Driver;
8
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...
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Str;
11
12
class CrudController extends Controller
13
{
14
15
    public function index()
16
    {
17
        return view('dbm::app');
18
    }
19
20
    public function all(Request $request)
21
    {
22
        if ($request->ajax()) {
23
24
            if (($response = DBM::authorize('crud.browse')) !== true) {
25
                return $response;
26
            }
27
28
            $perPage = (int) $request->perPage;
29
            $query   = $request->q;
30
31
            $userPermissions = DBM::userPermissions();
32
            $tables          = Table::paginate($perPage, null, [], $query);
33
            $objects         = DBM::Object()->all();
34
35
            $newTables = [];
36
37
            foreach ($tables as $table) {
38
                foreach ($objects as $object) {
39
                    if ($table == $object->name) {
40
                        $newTables[] = [
41
                            'name'   => $table,
42
                            'isCrud' => true,
43
                        ];
44
45
                        continue 2;
46
                    }
47
                }
48
49
                $newTables[] = [
50
                    'name'   => $table,
51
                    'isCrud' => false,
52
                ];
53
            }
54
55
            return response()->json([
56
                'success'         => true,
57
                'tables'          => $newTables,
58
                'userPermissions' => $userPermissions,
59
                'pagination'      => $tables,
60
            ]);
61
        }
62
63
        return response()->json(['success' => false]);
64
    }
65
66
    public function getObjectDetails(Request $request)
67
    {
68
        if ($request->ajax()) {
69
70
            try
71
            {
72
                if (!Table::exists($request->table)) {
73
74
                    throw new \Exception("Sorry! There is no table", 1);
75
76
                }
77
78
                $tableName           = $request->table;
79
                $namespace           = DBM::getModelNamespace();
80
                $relationship_tables = Table::all();
81
                $isCrudExists        = false;
82
83
                if ($object = DBM::Object()->where('name', $tableName)->first()) {
84
85
                    if (($response = DBM::authorize('crud.update')) !== true) {
86
                        return $response;
87
                    }
88
89
                    $isCrudExists = true;
90
91
                    if (!$object->model) {
92
                        $namespace = DBM::getModelNamespace();
93
94
                        $modelName = ucfirst(Str::singular($object->name));
95
96
                        $model         = $namespace . '\\' . $modelName;
97
                        $object->model = $model;
98
                    }
99
100
                    $fields = $object->fields()->orderBy('order', 'ASC')->get();
101
                } else {
102
                    if (($response = DBM::authorize('crud.create')) !== true) {
103
                        return $response;
104
                    }
105
                    $table = Table::getTable($tableName);
106
107
                    $modelName = ucfirst(Str::singular($table['name']));
108
                    $model     = $namespace . '\\' . $modelName;
109
110
                    $object               = new \stdClass;
111
                    $object->name         = $table['name'];
112
                    $object->slug         = Str::slug($table['name']);
113
                    $object->display_name = ucfirst($table['name']);
114
                    $object->model        = $model;
115
                    $object->controller   = '';
116
117
                    $fields = [];
118
                    $order  = 1;
119
120
                    foreach ($table['columns'] as $column) {
121
122
                        $fields[] = (object) [
123
                            'name'          => $column->name,
124
                            'display_name'  => ucfirst($column->name),
125
                            'type'          => DatabaseController::getInputType($column->type['name']),
126
                            'create'        => ($column->autoincrement) ? false : true,
127
                            'read'          => ($column->autoincrement) ? false : true,
128
                            'edit'          => ($column->autoincrement) ? false : true,
129
                            'delete'        => ($column->autoincrement) ? false : true,
130
                            'function_name' => '',
131
                            'order'         => $order,
132
                            'settings'      => '{ }',
133
                        ];
134
135
                        $order++;
136
                    }
137
                }
138
139
                $object->makeModel = false;
140
141
                $relationshipDetails = (object) [
142
                    'type'                => 'hasOne',
143
                    'foreignTableDetails' => Table::getTable($relationship_tables[0]),
144
                    'localTableDetails'   => Table::getTable($tableName),
145
146
                ];
147
148
            } catch (\Exception $e) {
149
                return response()->json([
150
                    'success' => false,
151
                    'errors'  => [$e->getMessage()],
152
                ], 400);
153
            }
154
155
            return response()->json([
156
                'success'              => true,
157
                'relationship_tables'  => $relationship_tables,
158
                'relationship_details' => $relationshipDetails,
159
                'object'               => $object,
160
                'fields'               => $fields,
161
                'isCrudExists'         => $isCrudExists,
162
                'userPermissions'      => DBM::userPermissions(),
163
                'driver'               => Driver::getConnectionName(),
164
            ]);
165
        }
166
167
        return response()->json(['success' => false]);
168
    }
169
170
    public function addCrud($table, $columns)
171
    {
172
        try
173
        {
174
            if ($table['model'] == '' || $table['model'] == null) {
175
                return response()->json([
176
                    'success' => false,
177
                    'errors'  => ["Model Must be provided"],
178
                ], 400);
179
180
            }
181
182
            if ($table['makeModel'] == true && !class_exists($table['model'])) {
183
                \DBM::makeModel($table['model'], $table['name']);
184
            } else if ($table['makeModel'] == false && !class_exists($table['model'])) {
185
                return response()->json([
186
                    'success' => false,
187
                    'errors'  => ["Create model '" . $table['model'] . "' first or checked create model option"],
188
                ], 400);
189
            }
190
191
            if (!class_exists($table['controller'])) {
192
                \DBM::makeController($table['controller']);
193
            }
194
195
            $object               = DBM::Object();
196
            $object->name         = $table['name'];
197
            $object->slug         = Str::slug($table['slug']);
198
            $object->display_name = ucfirst($table['display_name']);
199
            $object->model        = $table['model'];
200
            $object->controller   = $table['controller'];
201
            $object->details      = [
202
                'findColumn'         => $table['findColumn'],
203
                'searchColumn'       => $table['searchColumn'],
204
                'perPage'            => $table['perPage'],
205
                'orderColumn'        => $table['orderColumn'],
206
                'orderDisplayColumn' => $table['orderDisplayColumn'],
207
                'orderDirection'     => $table['orderDirection'],
208
            ];
209
210
            if ($object->save()) {
211
212
                foreach ($columns as $column) {
213
214
                    $field                = DBM::Field();
215
                    $field->dbm_object_id = $object->id;
216
                    $field->name          = $column['name'];
217
                    $field->display_name  = ucfirst($column['display_name']);
218
                    $field->type          = $column['type'];
219
                    // $field->required      = isset($column['required']) ? $column['required'] : false;
220
                    $field->create        = isset($column['create']) ? $column['create'] : false;
221
                    $field->read          = isset($column['read']) ? $column['read'] : false;
222
                    $field->edit          = isset($column['edit']) ? $column['edit'] : false;
223
                    $field->delete        = isset($column['delete']) ? $column['delete'] : false;
224
                    $field->order         = $column['order'];
225
                    $field->function_name = $column['function_name'];
226
                    $field->settings      = json_decode($column['settings']);
227
228
                    $field->save();
229
                }
230
231
            }
232
233
            return true;
234
235
        } catch (\Exception $e) {
236
            return $this->generateError([$e->getMessage()]);
237
        }
238
    }
239
240
    public function updateCrud($table, $columns)
241
    {
242
        try
243
        {
244
245
            if ($table['model'] == '' || $table['model'] == null) {
246
                return $this->generateError(["Model Must be provided"]);
247
248
            }
249
250
            if ($table['makeModel'] == true) {
251
                \DBM::makeModel($table['model'], $table['name']);
252
            } else if ($table['makeModel'] == false && !class_exists($table['model'])) {
253
                return $this->generateError(["Create mode '" . $table['model'] . "' first."]);
254
            }
255
256
            if (!class_exists($table['controller'])) {
257
                \DBM::makeController($table['controller']);
258
            }
259
260
            $object               = DBM::Object()->where('name', $table['name'])->first();
261
            $object->slug         = Str::slug($table['slug']);
262
            $object->display_name = ucfirst($table['display_name']);
263
            $object->model        = $table['model'];
264
            $object->controller   = $table['controller'];
265
            $object->details      = [
266
                'findColumn'         => $table['findColumn'],
267
                'searchColumn'       => $table['searchColumn'],
268
                'perPage'            => $table['perPage'],
269
                'orderColumn'        => $table['orderColumn'],
270
                'orderDisplayColumn' => $table['orderDisplayColumn'],
271
                'orderDirection'     => $table['orderDirection'],
272
            ];
273
274
            if ($object->update()) {
275
276
                foreach ($columns as $column) {
277
278
                    $field = DBM::Field()->where([
279
                        'dbm_object_id' => $object->id,
280
                        'name'          => $column['name'],
281
                    ])->first();
282
283
                    $field->display_name = ucfirst($column['display_name']);
284
                    $field->type         = $column['type'];
285
                    // $field->required      = isset($column['required']) ? $column['required'] : false;
286
                    $field->create        = isset($column['create']) ? $column['create'] : false;
287
                    $field->read          = isset($column['read']) ? $column['read'] : false;
288
                    $field->edit          = isset($column['edit']) ? $column['edit'] : false;
289
                    $field->delete        = isset($column['delete']) ? $column['delete'] : false;
290
                    $field->order         = $column['order'];
291
                    $field->function_name = isset($column['function_name']) ? $column['function_name'] : "";
292
                    $field->settings      = json_decode($column['settings']);
293
294
                    $field->update();
295
                }
296
            }
297
298
            return true;
299
300
        } catch (\Exception $e) {
301
            return $this->generateError([$e->getMessage()]);
302
        }
303
    }
304
305
    public function storeOrUpdate(Request $request)
306
    {
307
        if ($request->ajax()) {
308
309
            if (($response = DBM::authorize('crud.browse')) !== true) {
310
                return $response;
311
            }
312
313
            $table   = $request->object;
314
            $columns = $request->fields;
315
            $action  = ($request->isCrudExists) ? 'edit' : 'add';
316
317
            // return response()->json(['columns' => $columns, 'action' => $action]);
318
319
            if ($action == 'add') {
320
321
                if (($response = DBM::authorize('crud.create')) !== true) {
322
                    return $response;
323
                }
324
325
                $response = $this->addCrud($table, $columns);
326
327
                if ($response !== true) {
328
                    return $response;
329
                }
330
331
            } else if ($action == 'edit') {
332
333
                if (($response = DBM::authorize('crud.update')) !== true) {
334
                    return $response;
335
                }
336
337
                $response = $this->updateCrud($table, $columns);
338
339
                if ($response !== true) {
340
                    return $response;
341
                }
342
            }
343
344
            return response()->json([
345
                'success' => true,
346
                'object'  => $request->object,
347
                'fields'  => $request->fields,
348
            ]);
349
        }
350
351
        return response()->json(['success' => false]);
352
    }
353
354
    public function delete(Request $request)
355
    {
356
        if ($request->ajax()) {
357
358
            if (($response = DBM::authorize('crud.delete')) !== true) {
359
                return $response;
360
            }
361
362
            $object = DBM::Object()->where('name', $request->table)->first();
363
            if ($object) {
364
                $object->fields()->delete();
365
                $object->delete();
366
                return response()->json(['success' => true]);
367
            }
368
        }
369
370
        return response()->json(['success' => false]);
371
    }
372
    /*
373
     * RelationShip
374
     */
375
    public function getRelation(Request $request)
376
    {
377
        if ($request->ajax()) {
378
379
            if (($response = DBM::authorize('relationship.update')) !== true) {
380
                return $response;
381
            }
382
383
            $tableName = $request->table;
384
            $field     = json_decode($request->field);
385
386
            $object = DBM::Object()->where('name', $tableName)->first();
387
            $fields = $object->fields;
388
389
            $prefix = (Driver::isMongoDB()) ? "_" : "";
390
391
            foreach ($fields as $fld) {
392
                if ($fld->id == $field->{$prefix . "id"}) {
393
394
                    $relationship = $fld->settings;
395
                    $localTable   = $relationship['localTable'];
396
                    $foreignTable = $relationship['foreignTable'];
397
                    $pivotTable   = $relationship['pivotTable'];
398
399
                    $field->localFields   = Table::getTable($localTable);
400
                    $field->foreignFields = Table::getTable($foreignTable);
401
                    $field->pivotFields   = Table::getTable($pivotTable);
402
                    $field->relationship  = $relationship;
403
                }
404
            }
405
406
            return response()->json(['success' => true, 'field' => $field]);
407
        }
408
409
        return response()->json(['success' => false]);
410
    }
411
412
    public function addRelation(Request $request)
413
    {
414
        if ($request->ajax()) {
415
416
            if (($response = DBM::authorize('relationship.create')) !== true) {
417
                return $response;
418
            }
419
420
            $relationship = $request->relationship;
421
422
            // return response()->json(['success' => true, 'relationship' => $relationship['displayLevel']]);
423
424
            if (!class_exists($relationship['localModel'])) {
425
426
                $error = $relationship['localModel'] . " Model not found. Please create the " . $relationship['localModel'] . " model first";
427
                return $this->generateError([$error]);
428
            }
429
430
            if (!class_exists($relationship['foreignModel'])) {
431
432
                $error = $relationship['foreignModel'] . " Model not found. Please create the " . $relationship['foreignModel'] . " model first";
433
                return $this->generateError([$error]);
434
            }
435
436
            $fieldName = strtolower(Str::singular($relationship['localTable']) . '_' . $relationship['type'] . '_' . Str::singular($relationship['foreignTable']) . '_relationship');
437
            $settings  = [
438
                'relationType'    => $relationship['type'],
439
                'localModel'      => $relationship['localModel'],
440
                'localTable'      => $relationship['localTable'],
441
                'localKey'        => $relationship['localKey'],
442
                'foreignModel'    => $relationship['foreignModel'],
443
                'foreignTable'    => $relationship['foreignTable'],
444
                'foreignKey'      => $relationship['foreignKey'],
445
                'displayLabel'    => $relationship['displayLabel'],
446
                'pivotTable'      => $relationship['pivotTable'],
447
                'parentPivotKey'  => $relationship['parentPivotKey'],
448
                'relatedPivotKey' => $relationship['relatedPivotKey'],
449
            ];
450
451
            $object = DBM::Object()->where('name', $relationship['localTable'])->first();
452
            $order  = DBM::Field()->where('dbm_object_id', $object->id)->max('order');
453
454
            $field                = DBM::Field();
455
            $field->dbm_object_id = $object->id;
456
            $field->name          = $fieldName;
457
            $field->type          = 'relationship';
458
            $field->display_name  = ucfirst($relationship['foreignTable']);
459
            $field->order         = $order + 1;
460
            $field->settings      = $settings;
461
            if ($field->save()) {
462
                return response()->json(['success' => true]);
463
            }
464
        }
465
466
        return response()->json(['success' => false]);
467
    }
468
469
    public function updateRelation(Request $request)
470
    {
471
        if ($request->ajax()) {
472
473
            if (($response = DBM::authorize('relationship.update')) !== true) {
474
                return $response;
475
            }
476
477
            $relationship = $request->relationship;
478
            $field        = $request->field;
479
480
            // return response()->json(['relationship' => $relationship, 'field' => $field]);
481
482
            $settings = [
483
                'relationType'    => $relationship['type'],
484
                'localModel'      => $relationship['localModel'],
485
                'localTable'      => $relationship['localTable'],
486
                'localKey'        => $relationship['localKey'],
487
                'foreignModel'    => $relationship['foreignModel'],
488
                'foreignTable'    => $relationship['foreignTable'],
489
                'foreignKey'      => $relationship['foreignKey'],
490
                'displayLabel'    => $relationship['displayLabel'],
491
                'pivotTable'      => $relationship['pivotTable'],
492
                'parentPivotKey'  => $relationship['parentPivotKey'],
493
                'relatedPivotKey' => $relationship['relatedPivotKey'],
494
            ];
495
496
            $field           = DBM::Field()::find($field['id']);
497
            $field->settings = $settings;
498
            if ($field->update()) {
499
                return response()->json(['success' => true]);
500
            }
501
        }
502
503
        return response()->json(['success' => false]);
504
    }
505
506
    public function deleteRelation(Request $request)
507
    {
508
        if ($request->ajax()) {
509
510
            if (($response = DBM::authorize('relationship.delete')) !== true) {
511
                return $response;
512
            }
513
514
            $tableName = $request->table;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableName is dead and can be removed.
Loading history...
515
            $data      = json_decode($request->field);
516
517
            $field = DBM::Field()::find($data->id);
518
519
            if ($field->delete()) {
520
                return response()->json(['success' => true]);
521
            }
522
        }
523
524
        return response()->json(['success' => false]);
525
    }
526
527
    protected function generateError($errors)
528
    {
529
        return response()->json([
530
            'success' => false,
531
            'errors'  => $errors,
532
        ], 400);
533
    }
534
}
535