Completed
Push — master ( 7f1e16...35a352 )
by CodexShaper
05:06
created

CrudController::storeOrUpdate()   B

Complexity

Conditions 10
Paths 22

Size

Total Lines 45
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

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