Passed
Push — master ( 35a352...bdd975 )
by CodexShaper
04:16
created

CrudController   F

Complexity

Total Complexity 70

Size/Duplication

Total Lines 455
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 260
c 7
b 0
f 0
dl 0
loc 455
ccs 0
cts 353
cp 0
rs 2.8
wmc 70

13 Methods

Rating   Name   Duplication   Size   Complexity  
B all() 0 44 6
A index() 0 3 1
C getObjectDetails() 0 102 13
A checkModel() 0 16 6
B addOrUpdateField() 0 27 7
A updateRelation() 0 35 4
A addOrUpdateObject() 0 27 3
B addRelation() 0 55 6
B getRelation() 0 35 6
A deleteRelation() 0 19 4
A generateError() 0 6 1
B storeOrUpdate() 0 40 9
A delete() 0 17 4

How to fix   Complexity   

Complex Class

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

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 storeOrUpdate(Request $request)
171
    {
172
        if ($request->ajax()) {
173
174
            $table      = $request->object;
175
            $columns    = $request->fields;
176
            $permission = $request->isCrudExists ? 'update' : 'create';
177
178
            if (($response = DBM::authorize('crud.' . $permission)) !== true) {
179
                return $response;
180
            }
181
182
            if (($response = $this->checkModel($table)) !== true) {
183
                return $response;
184
            }
185
186
            if (!class_exists($table['controller'])) {
187
                \DBM::makeController($table['controller']);
188
            }
189
190
            try
191
            {
192
                if ($object = $this->addOrUpdateObject($table)) {
193
                    foreach ($columns as $column) {
194
                        $this->addOrUpdateField($column, $object);
195
                    }
196
197
                    return response()->json([
198
                        'success' => true,
199
                        'object'  => $request->object,
200
                        'fields'  => $request->fields,
201
                    ]);
202
                }
203
204
            } catch (\Exception $e) {
205
                return $this->generateError([$e->getMessage()]);
206
            }
207
        }
208
209
        return response()->json(['success' => false]);
210
    }
211
212
    public function checkModel($table)
213
    {
214
        if (empty($table['model'])) {
215
            return $this->generateError(["Model Must be provided"]);
216
        }
217
218
        if ($table['makeModel'] && !class_exists($table['model'])) {
219
            \DBM::makeModel($table['model'], $table['name']);
220
        }
221
222
        if (!$table['makeModel'] && !class_exists($table['model'])) {
223
            $error = "Create model {$table['model']} first or checked create model option";
224
            return $this->generateError([$error]);
225
        }
226
227
        return true;
228
    }
229
230
    public function addOrUpdateObject($table)
231
    {
232
        $object = DBM::Object()->where('name', $table['name'])->first();
233
        $action = 'update';
234
        if (!$object) {
235
            $object       = DBM::Object();
236
            $object->name = $table['name'];
237
            $action       = 'save';
238
        }
239
        $object->slug         = Str::slug($table['slug']);
240
        $object->display_name = ucfirst($table['display_name']);
241
        $object->model        = $table['model'];
242
        $object->controller   = $table['controller'];
243
        $object->details      = [
244
            'findColumn'         => $table['findColumn'],
245
            'searchColumn'       => $table['searchColumn'],
246
            'perPage'            => $table['perPage'],
247
            'orderColumn'        => $table['orderColumn'],
248
            'orderDisplayColumn' => $table['orderDisplayColumn'],
249
            'orderDirection'     => $table['orderDirection'],
250
        ];
251
252
        if ($object->{$action}()) {
253
            return $object;
254
        }
255
256
        return false;
257
    }
258
259
    public function addOrUpdateField($column, $object)
260
    {
261
        $field = DBM::Field()->where([
262
            'dbm_object_id' => $object->id,
263
            'name'          => $column['name'],
264
        ])->first();
265
266
        $action = 'update';
267
268
        if (!$field) {
269
            $field                = DBM::Field();
270
            $field->dbm_object_id = $object->id;
271
            $field->name          = $column['name'];
272
            $action               = 'save';
273
        }
274
275
        $field->display_name  = ucfirst($column['display_name']);
276
        $field->type          = $column['type'];
277
        $field->create        = isset($column['create']) ? $column['create'] : false;
278
        $field->read          = isset($column['read']) ? $column['read'] : false;
279
        $field->edit          = isset($column['edit']) ? $column['edit'] : false;
280
        $field->delete        = isset($column['delete']) ? $column['delete'] : false;
281
        $field->order         = $column['order'];
282
        $field->function_name = isset($column['function_name']) ? $column['function_name'] : "";
283
        $field->settings      = json_decode($column['settings']);
284
285
        $field->{$action}();
286
    }
287
288
    public function delete(Request $request)
289
    {
290
        if ($request->ajax()) {
291
292
            if (($response = DBM::authorize('crud.delete')) !== true) {
293
                return $response;
294
            }
295
296
            $object = DBM::Object()->where('name', $request->table)->first();
297
            if ($object) {
298
                $object->fields()->delete();
299
                $object->delete();
300
                return response()->json(['success' => true]);
301
            }
302
        }
303
304
        return response()->json(['success' => false]);
305
    }
306
    /*
307
     * RelationShip
308
     */
309
    public function getRelation(Request $request)
310
    {
311
        if ($request->ajax()) {
312
313
            if (($response = DBM::authorize('relationship.update')) !== true) {
314
                return $response;
315
            }
316
317
            $tableName = $request->table;
318
            $field     = json_decode($request->field);
319
320
            $object = DBM::Object()->where('name', $tableName)->first();
321
            $fields = $object->fields;
322
323
            $prefix = (Driver::isMongoDB()) ? "_" : "";
324
325
            foreach ($fields as $fld) {
326
                if ($fld->id == $field->{$prefix . "id"}) {
327
328
                    $relationship = $fld->settings;
329
                    $localTable   = $relationship['localTable'];
330
                    $foreignTable = $relationship['foreignTable'];
331
                    $pivotTable   = $relationship['pivotTable'];
332
333
                    $field->localFields   = Table::getTable($localTable);
334
                    $field->foreignFields = Table::getTable($foreignTable);
335
                    $field->pivotFields   = Table::getTable($pivotTable);
336
                    $field->relationship  = $relationship;
337
                }
338
            }
339
340
            return response()->json(['success' => true, 'field' => $field]);
341
        }
342
343
        return response()->json(['success' => false]);
344
    }
345
346
    public function addRelation(Request $request)
347
    {
348
        if ($request->ajax()) {
349
350
            if (($response = DBM::authorize('relationship.create')) !== true) {
351
                return $response;
352
            }
353
354
            $relationship = $request->relationship;
355
356
            // return response()->json(['success' => true, 'relationship' => $relationship['displayLevel']]);
357
358
            if (!class_exists($relationship['localModel'])) {
359
360
                $error = $relationship['localModel'] . " Model not found. Please create the " . $relationship['localModel'] . " model first";
361
                return $this->generateError([$error]);
362
            }
363
364
            if (!class_exists($relationship['foreignModel'])) {
365
366
                $error = $relationship['foreignModel'] . " Model not found. Please create the " . $relationship['foreignModel'] . " model first";
367
                return $this->generateError([$error]);
368
            }
369
370
            $fieldName = strtolower(Str::singular($relationship['localTable']) . '_' . $relationship['type'] . '_' . Str::singular($relationship['foreignTable']) . '_relationship');
371
            $settings  = [
372
                'relationType'    => $relationship['type'],
373
                'localModel'      => $relationship['localModel'],
374
                'localTable'      => $relationship['localTable'],
375
                'localKey'        => $relationship['localKey'],
376
                'foreignModel'    => $relationship['foreignModel'],
377
                'foreignTable'    => $relationship['foreignTable'],
378
                'foreignKey'      => $relationship['foreignKey'],
379
                'displayLabel'    => $relationship['displayLabel'],
380
                'pivotTable'      => $relationship['pivotTable'],
381
                'parentPivotKey'  => $relationship['parentPivotKey'],
382
                'relatedPivotKey' => $relationship['relatedPivotKey'],
383
            ];
384
385
            $object = DBM::Object()->where('name', $relationship['localTable'])->first();
386
            $order  = DBM::Field()->where('dbm_object_id', $object->id)->max('order');
387
388
            $field                = DBM::Field();
389
            $field->dbm_object_id = $object->id;
390
            $field->name          = $fieldName;
391
            $field->type          = 'relationship';
392
            $field->display_name  = ucfirst($relationship['foreignTable']);
393
            $field->order         = $order + 1;
394
            $field->settings      = $settings;
395
            if ($field->save()) {
396
                return response()->json(['success' => true]);
397
            }
398
        }
399
400
        return response()->json(['success' => false]);
401
    }
402
403
    public function updateRelation(Request $request)
404
    {
405
        if ($request->ajax()) {
406
407
            if (($response = DBM::authorize('relationship.update')) !== true) {
408
                return $response;
409
            }
410
411
            $relationship = $request->relationship;
412
            $field        = $request->field;
413
414
            // return response()->json(['relationship' => $relationship, 'field' => $field]);
415
416
            $settings = [
417
                'relationType'    => $relationship['type'],
418
                'localModel'      => $relationship['localModel'],
419
                'localTable'      => $relationship['localTable'],
420
                'localKey'        => $relationship['localKey'],
421
                'foreignModel'    => $relationship['foreignModel'],
422
                'foreignTable'    => $relationship['foreignTable'],
423
                'foreignKey'      => $relationship['foreignKey'],
424
                'displayLabel'    => $relationship['displayLabel'],
425
                'pivotTable'      => $relationship['pivotTable'],
426
                'parentPivotKey'  => $relationship['parentPivotKey'],
427
                'relatedPivotKey' => $relationship['relatedPivotKey'],
428
            ];
429
430
            $field           = DBM::Field()::find($field['id']);
431
            $field->settings = $settings;
432
            if ($field->update()) {
433
                return response()->json(['success' => true]);
434
            }
435
        }
436
437
        return response()->json(['success' => false]);
438
    }
439
440
    public function deleteRelation(Request $request)
441
    {
442
        if ($request->ajax()) {
443
444
            if (($response = DBM::authorize('relationship.delete')) !== true) {
445
                return $response;
446
            }
447
448
            $tableName = $request->table;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableName is dead and can be removed.
Loading history...
449
            $data      = json_decode($request->field);
450
451
            $field = DBM::Field()::find($data->id);
452
453
            if ($field->delete()) {
454
                return response()->json(['success' => true]);
455
            }
456
        }
457
458
        return response()->json(['success' => false]);
459
    }
460
461
    protected function generateError($errors)
462
    {
463
        return response()->json([
464
            'success' => false,
465
            'errors'  => $errors,
466
        ], 400);
467
    }
468
}
469