Completed
Push — master ( 6b425b...94fb52 )
by CodexShaper
05:22
created

RecordController::update()   C

Complexity

Conditions 14
Paths 25

Size

Total Lines 64
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 14
eloc 33
c 2
b 0
f 0
nc 25
nop 1
dl 0
loc 64
ccs 0
cts 47
cp 0
crap 210
rs 6.2666

How to fix   Long Method    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 CodexShaper\DBM\Traits\RecordHelper;
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 RecordController extends Controller
14
{
15
    use RecordHelper;
16
17
    public function index()
18
    {
19
        return view('dbm::app');
20
    }
21
22
    public function store(Request $request)
23
    {
24
        if ($request->ajax()) {
25
26
            if (($response = DBM::authorize('record.create')) !== true) {
27
                return $response;
28
            }
29
30
            $tableName       = $request->table;
31
            $originalColumns = Table::getColumnsName($tableName);
32
            $columns         = json_decode($request->columns);
33
            $fields          = json_decode($request->fields);
34
35
            $errors = $this->validation($fields, $columns);
36
37
            if (count($errors) > 0) {
38
                return $this->generateError($errors);
39
            }
40
41
            $object = DBM::Object()->where('name', $tableName)->first();
42
            $model  = $object->model;
43
44
            if (!class_exists($model)) {
45
                return $this->generateError(["Model not found. Please create model first"]);
46
            }
47
48
            try {
49
50
                $table = DBM::model($model, $tableName);
51
52
                foreach ($columns as $column => $value) {
53
                    if (in_array($column, $originalColumns)) {
54
55
                        if ($request->hasFile($column)) {
56
                            $value = $this->saveFiles($request, $column, $tableName);
57
                        }
58
59
                        if (!Driver::isMongoDB()) {
60
                            if ($functionName = $this->hasFunction($fields, $column)) {
61
                                $value = $this->executeFunction($functionName, $value);
62
                            }
63
                        }
64
65
                        $table->{$column} = $this->prepareStoreField($value, $tableName, $column);
66
                    }
67
                }
68
69
                if ($table->save()) {
70
                    $this->storeRelationshipData($fields, $columns, $object, $table);
71
                    return response()->json(['success' => true, 'object' => $object, 'table' => $table]);
72
                }
73
74
            } catch (\Exception $e) {
75
                return $this->generateError([$e->getMessage()]);
76
            }
77
        }
78
79
        return response()->json(['success' => false]);
80
    }
81
82
    public function saveFiles($request, $column, $tableName)
83
    {
84
        $files  = $request->file($column);
85
        $values = [];
86
        foreach ($files as $file) {
87
            $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
88
            $path     = 'public/dbm/' . $tableName;
89
            $file->storeAs($path, $fileName);
90
            $values[] = $fileName;
91
        }
92
93
        if (count($values) > 1) {
94
            $value = $values;
95
            if (!Driver::isMongoDB()) {
96
                $value = json_encode($values);
97
            }
98
        }
99
100
        if (count($values) == 1) {
101
            $value = $values[0];
102
        }
103
104
        return $value;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.
Loading history...
105
    }
106
107
    public function prepareStoreField($value, $tableName, $column)
108
    {
109
        $value = is_array($value) ? json_encode($value) : $value;
110
111
        if (Driver::isMongoDB()) {
112
113
            $fieldType = $this->getFieldType($tableName, $column);
114
115
            if (!in_array($fieldType, Type::getTypes())) {
116
                $this->generateError([$fieldType . " type not supported."]);
117
            }
118
119
            $value = Type::$fieldType($value);
120
121
        }
122
123
        return $value;
124
    }
125
126
    public function storeRelationshipData($fields, $columns, $object, $table)
127
    {
128
        foreach ($fields as $field) {
129
130
            if (isset($field->relationship) && $field->relationship->relationType == "belongsToMany") {
131
132
                $relationship = $field->relationship;
133
134
                $localModel      = $relationship->localModel;
135
                $localTable      = $relationship->localTable;
136
                $foreignModel    = $relationship->foreignModel;
137
                $pivotTable      = $relationship->pivotTable;
138
                $parentPivotKey  = $relationship->parentPivotKey;
139
                $relatedPivotKey = $relationship->relatedPivotKey;
140
141
                $findColumn = $object->details['findColumn'];
142
143
                $localObject = DBM::model($localModel, $localTable)::where($findColumn, $table->{$findColumn})->first();
144
145
                DBM::Object()
146
                    ->setManyToManyRelation(
147
                        $localObject,
148
                        $foreignModel,
149
                        $pivotTable,
150
                        $parentPivotKey,
151
                        $relatedPivotKey
152
                    )
153
                    ->belongs_to_many()
154
                    ->attach($columns->{$relatedPivotKey});
155
            }
156
        }
157
    }
158
159
    public function update(Request $request)
160
    {
161
        if ($request->ajax()) {
162
163
            if (($response = DBM::authorize('record.update')) !== true) {
164
                return $response;
165
            }
166
167
            $tableName       = $request->table;
168
            $originalColumns = Table::getColumnsName($tableName);
169
            $columns         = json_decode($request->columns);
170
            $fields          = json_decode($request->fields);
171
172
            $errors = $this->validation($fields, $columns, 'update');
173
174
            if (count($errors) > 0) {
175
                return $this->generateError($errors);
176
            }
177
178
            $object  = DBM::Object()->where('name', $tableName)->first();
179
            $model   = $object->model;
180
            $details = $object->details;
181
            $key     = $details['findColumn'];
182
183
            if (!class_exists($model)) {
184
                return $this->generateError(["Model not found. Please create model first"]);
185
            }
186
187
            try {
188
189
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
190
191
                foreach ($columns as $column => $value) {
192
193
                    if (in_array($column, $originalColumns)) {
194
195
                        if ($request->hasFile($column)) {
196
                            $value = $this->saveFiles($request, $column, $tableName);
197
                        }
198
199
                        if ($value !== null && $value !== "") {
200
201
                            if (!Driver::isMongoDB()) {
202
                                if ($functionName = $this->hasFunction($fields, $column)) {
203
                                    $value = $this->executeFunction($functionName, $value);
204
                                }
205
                            }
206
207
                            $table->{$column} = $this->prepareStoreField($value, $tableName, $column);
208
                        }
209
                    }
210
                }
211
212
                if ($table->update()) {
213
                    $this->updateRelationshipData($fields, $columns, $object, $table);
214
                    return response()->json(['success' => true]);
215
                }
216
217
            } catch (\Exception $e) {
218
                return $this->generateError([$e->getMessage()]);
219
            }
220
        }
221
222
        return response()->json(['success' => false]);
223
    }
224
225
    public function updateRelationshipData($fields, $columns, $object, $table)
226
    {
227
        foreach ($fields as $field) {
228
229
            if (isset($field->relationship)) {
230
231
                $relationship = $field->relationship;
232
233
                $localModel   = $relationship->localModel;
234
                $localTable   = $relationship->localTable;
235
                $foreignModel = $relationship->foreignModel;
236
237
                if ($field->relationship->relationType == "belongsToMany") {
238
                    $pivotTable      = $relationship->pivotTable;
239
                    $parentPivotKey  = $relationship->parentPivotKey;
240
                    $relatedPivotKey = $relationship->relatedPivotKey;
241
242
                    $findColumn = $object->details['findColumn'];
243
244
                    $localObject = DBM::model($localModel, $localTable)->where($findColumn, $table->{$findColumn})->first();
245
246
                    DBM::Object()
247
                        ->setManyToManyRelation(
248
                            $localObject,
249
                            $foreignModel,
250
                            $pivotTable,
251
                            $parentPivotKey,
252
                            $relatedPivotKey
253
                        )
254
                        ->belongs_to_many()
255
                        ->sync($columns->{$relatedPivotKey});
256
                }
257
258
            }
259
        }
260
    }
261
262
    public function delete(Request $request)
263
    {
264
        if ($request->ajax()) {
265
266
            if (($response = DBM::authorize('record.delete')) !== true) {
267
                return $response;
268
            }
269
270
            $tableName = $request->table;
271
            // $originalColumns = Table::getColumnsName($tableName);
272
            $columns = json_decode($request->columns);
273
            $fields  = $request->fields;
274
            $object  = DBM::Object()->where('name', $tableName)->first();
275
            $model   = $object->model;
276
            $details = $object->details;
277
            $key     = $details['findColumn'];
278
279
            if (!class_exists($model)) {
280
                return $this->generateError(["Model not found. Please create model first"]);
281
            }
282
283
            try {
284
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
285
                if ($table) {
286
                    // Remove Relationship data
287
                    foreach ($fields as $field) {
288
                        $field = json_decode($field);
289
                        $this->removeRelationshipData($field, $object, $table);
290
                    }
291
                    // Check Table deleted successfully
292
                    if ($table->delete()) {
293
                        return response()->json(['success' => true]);
294
                    }
295
                }
296
297
            } catch (\Exception $e) {
298
                return $this->generateError([$e->getMessage()]);
299
            }
300
        }
301
302
        return response()->json(['success' => false]);
303
    }
304
305
    public function getTableDetails(Request $request)
306
    {
307
        if ($request->ajax()) {
308
309
            if (($response = DBM::authorize('record.browse')) !== true) {
310
                return $response;
311
            }
312
313
            $tableName = $request->table;
314
            $object    = DBM::Object()->where('name', $tableName)->first();
315
316
            if (!$object) {
317
                return response()->json([
318
                    'success' => false,
319
                    'errors'  => ["There is no Object details"],
320
                ], 400);
321
            }
322
323
            $createFields     = $object->createFields();
324
            $browseFields     = $object->readFields();
325
            $editFields       = $object->editFields();
326
            $deleteFields     = $object->deleteFields();
327
            $fields           = $object->allFields();
328
            $foreignTableData = [];
329
330
            $createFields = $this->prepareRecordFields($createFields);
331
            $editFields   = $this->prepareRecordFields($editFields);
332
333
            $model = $object->model;
334
335
            if (!class_exists($model)) {
336
                return $this->generateError(["Model not found. Please create model first"]);
337
            }
338
339
            $perPage      = (int) $request->perPage;
340
            $query        = $request->q;
341
            $searchColumn = $object->details['searchColumn'];
342
            $records      = DBM::model($model, $tableName)->paginate($perPage);
343
344
            if (!empty($query) && !empty($searchColumn)) {
345
                $records = DBM::model($model, $tableName)
346
                    ->where($searchColumn, 'LIKE', '%' . $query . '%')
347
                    ->paginate($perPage);
348
            }
349
350
            $records       = $this->prepareRelationshipData($records, $browseFields, $object);
351
            $recordsDetail = $this->prepareJsonFieldData($records, $fields, $object, $request->findValue);
352
353
            $objectDetails            = $object->details;
354
            $objectDetails['perPage'] = $perPage;
355
356
            return response()->json([
357
                'success'          => true,
358
                'object'           => $object,
359
                'objectDetails'    => $objectDetails,
360
                'createFields'     => $createFields,
361
                'browseFields'     => $browseFields,
362
                'editFields'       => $editFields,
363
                'deleteFields'     => $deleteFields,
364
                'records'          => $recordsDetail['records'],
365
                'record'           => $recordsDetail['record'],
366
                'foreignTableData' => $foreignTableData,
367
                'userPermissions'  => DBM::userPermissions(),
368
                'pagination'       => $records,
369
            ]);
370
        }
371
372
        return response()->json(['success' => false]);
373
    }
374
375
    public function prepareRecordFields($fields)
376
    {
377
        foreach ($fields as $key => $field) {
378
379
            if ($field->type == 'relationship') {
380
381
                $relationship            = $field->settings;
382
                $foreignModel            = $relationship['foreignModel'];
383
                $foreignKey              = $relationship['foreignKey'];
384
                $fields                  = $this->removeRelationshipKeyForBelongsTo($fields, $foreignKey);
385
                $field->foreignTableData = $foreignModel::all();
386
                $field->relationship     = $relationship;
387
                continue;
388
            }
389
390
            if (isset($field->settings['options'])) {
391
                $options = $this->getSettingOptions($field);
392
                if (is_array($options)) {
393
                    $fields[$key]->options = $options;
394
                }
395
            }
396
        }
397
398
        return $fields;
399
    }
400
401
    public function prepareJsonFieldData($records, $fields, $object, $findValue)
402
    {
403
        $newRecords = [];
404
        $newRecord  = new \stdClass();
405
406
        foreach ($records as $item => $record) {
407
408
            foreach ($fields as $key => &$field) {
409
410
                if (isset($record->{$field->name})) {
411
412
                    $record->{$field->name} = is_json($record->{$field->name}) ? json_decode($record->{$field->name}, true) : $record->{$field->name};
413
                }
414
            }
415
416
            if ($findValue && $record->{$object->details['findColumn']} == $findValue) {
417
                $newRecord = $record;
418
            }
419
420
            $newRecords[] = $record;
421
        }
422
423
        return [
424
            "records" => $newRecords,
425
            "record"  => $newRecord,
426
        ];
427
    }
428
429
    public function prepareRelationshipData($records, $browseFields, $object)
430
    {
431
        foreach ($records as $item => $record) {
432
433
            foreach ($browseFields as $field) {
434
435
                if ($field->type == 'relationship') {
436
437
                    $relationship = $field->settings;
438
439
                    $findColumn = $object->details['findColumn'];
440
441
                    $localModel       = $relationship['localModel'];
442
                    $localKey         = $relationship['localKey'];
443
                    $foreignModel     = $relationship['foreignModel'];
444
                    $foreignKey       = $relationship['foreignKey'];
445
                    $relationshipType = $relationship['relationType'];
446
                    $displayLabel     = $relationship['displayLabel'];
447
448
                    if ($relationshipType == 'belongsTo') {
449
450
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
451
452
                        $datas = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->belongs_to;
453
454
                        $record->{$field->name}  = $datas;
455
                        $field->displayLabel     = $displayLabel;
456
                        $field->localKey         = $localKey;
457
                        $field->foreignKey       = $foreignKey;
458
                        $field->relationshipType = $relationshipType;
459
460
                    } else if ($relationshipType == 'hasMany') {
461
462
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
463
                        $datas       = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->has_many;
464
465
                        $record->{$field->name}  = $datas;
466
                        $field->displayLabel     = $displayLabel;
467
                        $field->localKey         = $localKey;
468
                        $field->foreignKey       = $foreignKey;
469
                        $field->relationshipType = $relationshipType;
470
471
                    } else if ($relationshipType == 'belongsToMany') {
472
473
                        $pivotTable      = $relationship['pivotTable'];
474
                        $parentPivotKey  = $relationship['parentPivotKey'];
475
                        $relatedPivotKey = $relationship['relatedPivotKey'];
476
477
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
478
479
                        $datas = DBM::Object()->setManyToManyRelation($localObject, $foreignModel, $pivotTable, $parentPivotKey, $relatedPivotKey)->belongs_to_many;
480
481
                        $record->{$field->name}  = $datas;
482
                        $field->displayLabel     = $displayLabel;
483
                        $field->localKey         = $localKey;
484
                        $field->foreignKey       = $foreignKey;
485
                        $field->relationshipType = $relationshipType;
486
                    }
487
                }
488
            }
489
        }
490
491
        return $records;
492
    }
493
}
494