Completed
Push — master ( 3739d9...3d27ba )
by CodexShaper
05:01
created

RecordController::removeRelationshipKeyForBelongsTo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 13
ccs 0
cts 11
cp 0
crap 12
rs 10
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;
0 ignored issues
show
introduced by
The trait CodexShaper\DBM\Traits\RecordHelper requires some properties which are not provided by CodexShaper\DBM\Http\Controllers\RecordController: $name, $function_name, $localModel, $create, $relatedPivotKey, $parentPivotKey, $relationType, $details, $rules, $update, $type, $settings, $validation, $pivotTable, $foreignModel
Loading history...
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
            // return response()->json(['columns' => $columns]);
36
37
            $errors = $this->validation($fields, $columns);
38
39
            if (count($errors) > 0) {
40
                return $this->generateError($errors);
41
            }
42
43
            $object = DBM::Object()->where('name', $tableName)->first();
44
            $model  = $object->model;
45
46
            if (!class_exists($model)) {
47
                return $this->generateError(["Model not found. Please create model first"]);
48
            }
49
50
            try {
51
52
                $table = DBM::model($model, $tableName);
53
54
                foreach ($columns as $column => $value) {
55
                    // $column = $field->name;
56
                    // $value  = $request->{$column};
57
                    if (in_array($column, $originalColumns)) {
58
59
                        if ($request->hasFile($column)) {
60
                            $files  = $request->file($column);
61
                            $values = [];
62
                            foreach ($files as $file) {
63
                                $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
64
                                $path     = 'public/dbm/' . $tableName;
65
                                $file->storeAs($path, $fileName);
66
                                $values[] = $fileName;
67
                            }
68
69
                            // $value = json_encode($values);
70
71
                            if (count($values) > 1) {
72
                                $value = $values;
73
                                if (!Driver::isMongoDB()) {
74
                                    $value = is_array($values) ? json_encode($values) : $values;
75
                                }
76
                            } else if (count($values) == 1) {
77
                                $value = $values[0];
78
                            }
79
                        }
80
81
                        if (!Driver::isMongoDB()) {
82
                            if ($functionName = $this->hasFunction($fields, $column)) {
83
                                $value = $this->executeFunction($functionName, $value);
84
                            }
85
                        }
86
87
                        // if ($value != "" || !empty($value)) {
88
89
                        $table->{$column} = is_array($value) ? json_encode($value) : $value;
90
91
                        if (Driver::isMongoDB()) {
92
93
                            $fieldType = $this->getFieldType($tableName, $column);
94
95
                            if (!in_array($fieldType, Type::getTypes())) {
96
                                $this->generateError([$fieldType . " type not supported."]);
97
                            }
98
99
                            $table->{$column} = Type::$fieldType($value);
100
101
                        }
102
                        // }
103
104
                    }
105
                }
106
107
                if ($table->save()) {
108
109
                    foreach ($fields as $field) {
110
111
                        if (isset($field->relationship) && $field->relationship->relationType == "belongsToMany") {
112
113
                            $relationship = $field->relationship;
114
115
                            $localModel      = $relationship->localModel;
116
                            $localTable      = $relationship->localTable;
117
                            $foreignModel    = $relationship->foreignModel;
118
                            $pivotTable      = $relationship->pivotTable;
119
                            $parentPivotKey  = $relationship->parentPivotKey;
120
                            $relatedPivotKey = $relationship->relatedPivotKey;
121
122
                            $findColumn = $object->details['findColumn'];
123
124
                            $localObject = DBM::model($localModel, $localTable)::where($findColumn, $table->{$findColumn})->first();
125
126
                            DBM::Object()
127
                                ->setManyToManyRelation(
128
                                    $localObject,
129
                                    $foreignModel,
130
                                    $pivotTable,
131
                                    $parentPivotKey,
132
                                    $relatedPivotKey
133
                                )
134
                                ->belongs_to_many()
135
                                ->attach($columns->{$relatedPivotKey});
136
137
                        }
138
139
                        // else if (isset($field['relationship']) && $field['relationship']['relationType'] == "hasMany") {
140
141
                        //     $relationship = $field['relationship'];
142
143
                        //     $localModel   = $relationship['localModel'];
144
                        //     $findColumn   = $object->details['findColumn'];
145
                        //     $foreignModel = $relationship['foreignModel'];
146
                        //     $foreignKey   = $relationship['foreignKey'];
147
                        //     $localKey     = $relationship['localKey'];
148
149
                        //     $localObject = $localModel::where($findColumn, $table->{$findColumn})->first();
150
151
                        //     $items = [];
152
153
                        //     foreach ($columns[$foreignKey] as $key => $value) {
154
                        //         // return response()->json(['columns' => $columns['menu_id'], 'fields' => $value, 'model' => $foreignModel]);
155
                        //         $originalColumns    = Table::getColumnsName($relationship['foreignTable']);
156
                        //         $foreignTableFields = DBM::Object()->where('name', $relationship['foreignTable'])->first()->fields()->where('create', 1)->get();
157
158
                        //         $oldItem = $foreignModel::find($value);
159
                        //         $item    = new $foreignModel;
160
161
                        //         foreach ($foreignTableFields as $foreignTableField) {
162
                        //             if (in_array($foreignTableField->name, $originalColumns)) {
163
                        //                 if ($foreignTableField->name != $foreignKey) {
164
                        //                     $item->{$foreignTableField->name} = $oldItem->{$foreignTableField->name};
165
                        //                 }
166
                        //             }
167
                        //         }
168
                        //         DBM::Object()
169
                        //             ->setCommonRelation(
170
                        //                 $localObject,
171
                        //                 $foreignModel,
172
                        //                 $foreignKey,
173
                        //                 $localKey)
174
                        //             ->has_many()
175
                        //             ->save($item);
176
                        //     }
177
178
                        // }
179
                    }
180
                    return response()->json(['success' => true, 'object' => $object, 'table' => $table]);
181
                }
182
183
            } catch (\Exception $e) {
184
                return $this->generateError([$e->getMessage()]);
185
            }
186
        }
187
188
        return response()->json(['success' => false]);
189
    }
190
191
    public function update(Request $request)
192
    {
193
        if ($request->ajax()) {
194
195
            if (($response = DBM::authorize('record.update')) !== true) {
196
                return $response;
197
            }
198
199
            $tableName       = $request->table;
200
            $originalColumns = Table::getColumnsName($tableName);
201
            $columns         = json_decode($request->columns);
202
            $fields          = json_decode($request->fields);
203
204
            // return response()->json(['columns' => $columns->multiple_dropdown]);
205
206
            $errors = $this->validation($fields, $columns, 'update');
207
208
            if (count($errors) > 0) {
209
                return $this->generateError($errors);
210
            }
211
212
            $object  = DBM::Object()->where('name', $tableName)->first();
213
            $model   = $object->model;
214
            $details = $object->details;
215
            $key     = $details['findColumn'];
216
217
            if (!class_exists($model)) {
218
                return $this->generateError(["Model not found. Please create model first"]);
219
            }
220
221
            try {
222
223
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
224
225
                // return response()->json(['details' => $table, 'key' => $key]);
226
227
                foreach ($columns as $column => $value) {
228
                    // $column = $field->name;
229
                    // $value = $request->{$column};
230
231
                    if (in_array($column, $originalColumns)) {
232
233
                        if ($request->hasFile($column)) {
234
                            $files  = $request->file($column);
235
                            $values = [];
236
                            foreach ($files as $file) {
237
                                $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
238
                                $path     = 'public/dbm/' . $tableName;
239
                                $file->storeAs($path, $fileName);
240
                                $values[] = $fileName;
241
                            }
242
243
                            // $value = json_encode($values);
244
245
                            if (count($values) > 1) {
246
                                $value = $values;
247
                                if (!Driver::isMongoDB()) {
248
                                    $value = is_array($values) ? json_encode($values) : $value;
249
                                }
250
                            } else if (count($values) == 1) {
251
                                $value = $values[0];
252
                            }
253
                        }
254
255
                        if ($value !== null && $value !== "") {
256
257
                            if (!Driver::isMongoDB()) {
258
                                if ($functionName = $this->hasFunction($fields, $column)) {
259
260
                                    $value = $this->executeFunction($functionName, $value);
261
                                }
262
                            }
263
264
                            $table->{$column} = is_array($value) ? json_encode($value) : $value;
265
266
                            if (Driver::isMongoDB()) {
267
268
                                $fieldType = $this->getFieldType($tableName, $column);
269
270
                                if (!in_array($fieldType, Type::getTypes())) {
271
                                    $this->generateError([$fieldType . " type not supported."]);
272
                                }
273
274
                                $table->{$column} = Type::$fieldType($value);
275
276
                            }
277
                        }
278
                    }
279
                }
280
281
                if ($table->update()) {
282
283
                    foreach ($fields as $field) {
284
285
                        // return response()->json(['fields' => $fields]);
286
287
                        if (isset($field->relationship)) {
288
289
                            $relationship = $field->relationship;
290
291
                            $localModel   = $relationship->localModel;
292
                            $localTable   = $relationship->localTable;
293
                            $foreignModel = $relationship->foreignModel;
294
295
                            if ($field->relationship->relationType == "belongsToMany") {
296
                                $pivotTable      = $relationship->pivotTable;
297
                                $parentPivotKey  = $relationship->parentPivotKey;
298
                                $relatedPivotKey = $relationship->relatedPivotKey;
299
300
                                $findColumn = $object->details['findColumn'];
301
302
                                $localObject = DBM::model($localModel, $localTable)->where($findColumn, $table->{$findColumn})->first();
303
304
                                DBM::Object()
305
                                    ->setManyToManyRelation(
306
                                        $localObject,
307
                                        $foreignModel,
308
                                        $pivotTable,
309
                                        $parentPivotKey,
310
                                        $relatedPivotKey
311
                                    )
312
                                    ->belongs_to_many()
313
                                    ->sync($columns->{$relatedPivotKey});
314
                            }
315
316
                        }
317
                    }
318
319
                    return response()->json(['success' => true]);
320
                }
321
322
            } catch (\Exception $e) {
323
                return $this->generateError([$e->getMessage()]);
324
            }
325
        }
326
327
        return response()->json(['success' => false]);
328
    }
329
330
    public function delete(Request $request)
331
    {
332
        if ($request->ajax()) {
333
334
            if (($response = DBM::authorize('record.delete')) !== true) {
335
                return $response;
336
            }
337
338
            $tableName = $request->table;
339
            // $originalColumns = Table::getColumnsName($tableName);
340
            $columns = json_decode($request->columns);
341
            $fields  = $request->fields;
342
            $object  = DBM::Object()->where('name', $tableName)->first();
343
            $model   = $object->model;
344
            $details = $object->details;
345
            $key     = $details['findColumn'];
346
347
            if (!class_exists($model)) {
348
                return $this->generateError(["Model not found. Please create model first"]);
349
            }
350
351
            try {
352
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
353
                if ($table) {
354
                    // Remove Relationship data
355
                    foreach ($fields as $field) {
356
                        $field = json_decode($field);
357
                        $this->removeRelationshipData($field, $object, $table);
358
                    }
359
                    // Check Table deleted successfully
360
                    if ($table->delete()) {
361
                        return response()->json(['success' => true]);
362
                    }
363
                }
364
365
            } catch (\Exception $e) {
366
                return $this->generateError([$e->getMessage()]);
367
            }
368
        }
369
370
        return response()->json(['success' => false]);
371
    }
372
373
    public function getTableDetails(Request $request)
374
    {
375
        if ($request->ajax()) {
376
377
            if (($response = DBM::authorize('record.browse')) !== true) {
378
                return $response;
379
            }
380
381
            $tableName = $request->table;
382
            $object    = DBM::Object()->where('name', $tableName)->first();
383
384
            if (!$object) {
385
                return response()->json([
386
                    'success' => false,
387
                    'errors'  => ["There is no Object details"],
388
                ], 400);
389
            }
390
391
            $createFields     = $object->createFields();
392
            $browseFields     = $object->readFields();
393
            $editFields       = $object->editFields();
394
            $deleteFields     = $object->deleteFields();
395
            $fields           = $object->allFields();
396
            $foreignTableData = [];
397
398
            // return response()->json(['createFields' => auth()->user()]);
399
400
            foreach ($createFields as $key => $field) {
401
402
                if ($field->type == 'relationship') {
403
404
                    $relationship = $field->settings;
405
                    // $relationshipType = $relationship['relationType'];
406
                    // $localModel       = $relationship['localModel'];
407
                    // $localKey         = $relationship['localKey'];
408
                    $foreignModel = $relationship['foreignModel'];
409
                    $foreignKey   = $relationship['foreignKey'];
410
                    // $relationshipType = $relationship['relationType'];
411
412
                    // if ($relationshipType == 'belongsTo') {
413
                    $createFields            = $this->removeRelationshipKeyForBelongsTo($createFields, $foreignKey);
414
                    $field->foreignTableData = $foreignModel::all();
415
                    $field->relationship     = $relationship;
416
                    // } else {
417
                    //     unset($fields[$key]);
418
                    // }
419
                } else {
420
                    if (isset($field->settings['options'])) {
421
                        $options = $this->getSettingOptions($field);
422
                        if (is_array($options)) {
423
                            $createFields[$key]->options = $options;
424
                        }
425
                    }
426
427
                }
428
            }
429
430
            foreach ($editFields as $key => $field) {
431
432
                if ($field->type == 'relationship') {
433
434
                    $relationship = $field->settings;
435
                    // $relationshipType = $relationship['relationType'];
436
                    // $localModel       = $relationship['localModel'];
437
                    // $localKey         = $relationship['localKey'];
438
                    $foreignModel = $relationship['foreignModel'];
439
                    $foreignKey   = $relationship['foreignKey'];
440
                    // $relationshipType = $relationship['relationType'];
441
442
                    // if ($relationshipType == 'belongsTo') {
443
                    $editFields              = $this->removeRelationshipKeyForBelongsTo($editFields, $foreignKey);
444
                    $field->foreignTableData = $foreignModel::all();
445
                    $field->relationship     = $relationship;
446
                    // } else {
447
                    //     unset($fields[$key]);
448
                    // }
449
                    continue;
450
                }
451
452
                if (isset($field->settings['options'])) {
453
                    $options = $this->getSettingOptions($field);
454
                    if (is_array($options)) {
455
                        $editFields[$key]->options = $options;
456
                    }
457
                }
458
            }
459
            $model = $object->model;
460
461
            if (!class_exists($model)) {
462
                return $this->generateError(["Model not found. Please create model first"]);
463
            }
464
465
            $perPage = (int) $request->perPage;
466
            $query   = $request->q;
467
468
            $searchColumn = $object->details['searchColumn'];
469
470
            $records = DBM::model($model, $tableName)->paginate($perPage);
471
472
            // return response()->json(['success' => $perPage]);
473
474
            if (!empty($query) && !empty($searchColumn)) {
475
                $records = DBM::model($model, $tableName)
476
                    ->where($searchColumn, 'LIKE', '%' . $query . '%')
477
                    ->paginate($perPage);
478
            }
479
480
            foreach ($records as $item => $record) {
481
482
                foreach ($browseFields as $field) {
483
484
                    if ($field->type == 'relationship') {
485
486
                        $relationship = $field->settings;
487
488
                        $findColumn = $object->details['findColumn'];
489
490
                        $localModel       = $relationship['localModel'];
491
                        $localKey         = $relationship['localKey'];
492
                        $foreignModel     = $relationship['foreignModel'];
493
                        $foreignKey       = $relationship['foreignKey'];
494
                        $relationshipType = $relationship['relationType'];
495
                        $displayLabel     = $relationship['displayLabel'];
496
497
                        if ($relationshipType == 'belongsTo') {
498
499
                            $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
500
501
                            $datas = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->belongs_to;
502
503
                            $record->{$field->name}  = $datas;
504
                            $field->displayLabel     = $displayLabel;
505
                            $field->localKey         = $localKey;
506
                            $field->foreignKey       = $foreignKey;
507
                            $field->relationshipType = $relationshipType;
508
509
                        } else if ($relationshipType == 'hasMany') {
510
511
                            $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
512
                            $datas       = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->has_many;
513
514
                            $record->{$field->name}  = $datas;
515
                            $field->displayLabel     = $displayLabel;
516
                            $field->localKey         = $localKey;
517
                            $field->foreignKey       = $foreignKey;
518
                            $field->relationshipType = $relationshipType;
519
520
                        } else if ($relationshipType == 'belongsToMany') {
521
522
                            $pivotTable      = $relationship['pivotTable'];
523
                            $parentPivotKey  = $relationship['parentPivotKey'];
524
                            $relatedPivotKey = $relationship['relatedPivotKey'];
525
526
                            $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
527
528
                            $datas = DBM::Object()->setManyToManyRelation($localObject, $foreignModel, $pivotTable, $parentPivotKey, $relatedPivotKey)->belongs_to_many;
529
530
                            $record->{$field->name}  = $datas;
531
                            $field->displayLabel     = $displayLabel;
532
                            $field->localKey         = $localKey;
533
                            $field->foreignKey       = $foreignKey;
534
                            $field->relationshipType = $relationshipType;
535
                        }
536
                    }
537
                }
538
            }
539
540
            $newRecords = [];
541
            $newRecord  = new \stdClass;
542
543
            foreach ($records as $item => $record) {
544
545
                foreach ($fields as $key => &$field) {
546
547
                    if (isset($record->{$field->name})) {
548
549
                        $record->{$field->name} = is_json($record->{$field->name}) ? json_decode($record->{$field->name}, true) : $record->{$field->name};
550
                    }
551
                }
552
553
                if ($request->findValue && $record->{$object->details['findColumn']} == $request->findValue) {
554
                    $newRecord = $record;
555
                }
556
557
                $newRecords[] = $record;
558
            }
559
560
            $objectDetails            = $object->details;
561
            $objectDetails['perPage'] = $perPage;
562
563
            return response()->json([
564
                'success'          => true,
565
                'object'           => $object,
566
                'objectDetails'    => $objectDetails,
567
                'createFields'     => $createFields,
568
                'browseFields'     => $browseFields,
569
                'editFields'       => $editFields,
570
                'deleteFields'     => $deleteFields,
571
                'records'          => $newRecords,
572
                'record'           => $newRecord,
573
                'foreignTableData' => $foreignTableData,
574
                'userPermissions'  => DBM::userPermissions(),
575
                'pagination'       => $records,
576
            ]);
577
        }
578
579
        return response()->json(['success' => false]);
580
    }
581
}
582