Completed
Push — master ( 0d3fe1...6b425b )
by CodexShaper
05:51
created

RecordController::storeRelationshipData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 20
c 1
b 0
f 0
nc 3
nop 4
dl 0
loc 29
ccs 0
cts 23
cp 0
crap 20
rs 9.6
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 = is_array($values) ? json_encode($values) : $values;
0 ignored issues
show
introduced by
The condition is_array($values) is always true.
Loading history...
97
            }
98
        } else if (count($values) == 1) {
99
            $value = $values[0];
100
        }
101
102
        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...
103
    }
104
105
    public function prepareStoreField($value, $tableName, $column)
106
    {
107
        $value = is_array($value) ? json_encode($value) : $value;
108
109
        if (Driver::isMongoDB()) {
110
111
            $fieldType = $this->getFieldType($tableName, $column);
112
113
            if (!in_array($fieldType, Type::getTypes())) {
114
                $this->generateError([$fieldType . " type not supported."]);
115
            }
116
117
            $value = Type::$fieldType($value);
118
119
        }
120
121
        return $value;
122
    }
123
124
    public function storeRelationshipData($fields, $columns, $object, $table)
125
    {
126
        foreach ($fields as $field) {
127
128
            if (isset($field->relationship) && $field->relationship->relationType == "belongsToMany") {
129
130
                $relationship = $field->relationship;
131
132
                $localModel      = $relationship->localModel;
133
                $localTable      = $relationship->localTable;
134
                $foreignModel    = $relationship->foreignModel;
135
                $pivotTable      = $relationship->pivotTable;
136
                $parentPivotKey  = $relationship->parentPivotKey;
137
                $relatedPivotKey = $relationship->relatedPivotKey;
138
139
                $findColumn = $object->details['findColumn'];
140
141
                $localObject = DBM::model($localModel, $localTable)::where($findColumn, $table->{$findColumn})->first();
142
143
                DBM::Object()
144
                    ->setManyToManyRelation(
145
                        $localObject,
146
                        $foreignModel,
147
                        $pivotTable,
148
                        $parentPivotKey,
149
                        $relatedPivotKey
150
                    )
151
                    ->belongs_to_many()
152
                    ->attach($columns->{$relatedPivotKey});
153
            }
154
        }
155
    }
156
157
    public function update(Request $request)
158
    {
159
        if ($request->ajax()) {
160
161
            if (($response = DBM::authorize('record.update')) !== true) {
162
                return $response;
163
            }
164
165
            $tableName       = $request->table;
166
            $originalColumns = Table::getColumnsName($tableName);
167
            $columns         = json_decode($request->columns);
168
            $fields          = json_decode($request->fields);
169
170
            // return response()->json(['columns' => $columns->multiple_dropdown]);
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
                // return response()->json(['details' => $table, 'key' => $key]);
192
193
                foreach ($columns as $column => $value) {
194
                    // $column = $field->name;
195
                    // $value = $request->{$column};
196
197
                    if (in_array($column, $originalColumns)) {
198
199
                        if ($request->hasFile($column)) {
200
                            $files  = $request->file($column);
201
                            $values = [];
202
                            foreach ($files as $file) {
203
                                $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
204
                                $path     = 'public/dbm/' . $tableName;
205
                                $file->storeAs($path, $fileName);
206
                                $values[] = $fileName;
207
                            }
208
209
                            // $value = json_encode($values);
210
211
                            if (count($values) > 1) {
212
                                $value = $values;
213
                                if (!Driver::isMongoDB()) {
214
                                    $value = is_array($values) ? json_encode($values) : $value;
215
                                }
216
                            } else if (count($values) == 1) {
217
                                $value = $values[0];
218
                            }
219
                        }
220
221
                        if ($value !== null && $value !== "") {
222
223
                            if (!Driver::isMongoDB()) {
224
                                if ($functionName = $this->hasFunction($fields, $column)) {
225
226
                                    $value = $this->executeFunction($functionName, $value);
227
                                }
228
                            }
229
230
                            $table->{$column} = is_array($value) ? json_encode($value) : $value;
231
232
                            if (Driver::isMongoDB()) {
233
234
                                $fieldType = $this->getFieldType($tableName, $column);
235
236
                                if (!in_array($fieldType, Type::getTypes())) {
237
                                    $this->generateError([$fieldType . " type not supported."]);
238
                                }
239
240
                                $table->{$column} = Type::$fieldType($value);
241
242
                            }
243
                        }
244
                    }
245
                }
246
247
                if ($table->update()) {
248
249
                    foreach ($fields as $field) {
250
251
                        // return response()->json(['fields' => $fields]);
252
253
                        if (isset($field->relationship)) {
254
255
                            $relationship = $field->relationship;
256
257
                            $localModel   = $relationship->localModel;
258
                            $localTable   = $relationship->localTable;
259
                            $foreignModel = $relationship->foreignModel;
260
261
                            if ($field->relationship->relationType == "belongsToMany") {
262
                                $pivotTable      = $relationship->pivotTable;
263
                                $parentPivotKey  = $relationship->parentPivotKey;
264
                                $relatedPivotKey = $relationship->relatedPivotKey;
265
266
                                $findColumn = $object->details['findColumn'];
267
268
                                $localObject = DBM::model($localModel, $localTable)->where($findColumn, $table->{$findColumn})->first();
269
270
                                DBM::Object()
271
                                    ->setManyToManyRelation(
272
                                        $localObject,
273
                                        $foreignModel,
274
                                        $pivotTable,
275
                                        $parentPivotKey,
276
                                        $relatedPivotKey
277
                                    )
278
                                    ->belongs_to_many()
279
                                    ->sync($columns->{$relatedPivotKey});
280
                            }
281
282
                        }
283
                    }
284
285
                    return response()->json(['success' => true]);
286
                }
287
288
            } catch (\Exception $e) {
289
                return $this->generateError([$e->getMessage()]);
290
            }
291
        }
292
293
        return response()->json(['success' => false]);
294
    }
295
296
    public function delete(Request $request)
297
    {
298
        if ($request->ajax()) {
299
300
            if (($response = DBM::authorize('record.delete')) !== true) {
301
                return $response;
302
            }
303
304
            $tableName = $request->table;
305
            // $originalColumns = Table::getColumnsName($tableName);
306
            $columns = json_decode($request->columns);
307
            $fields  = $request->fields;
308
            $object  = DBM::Object()->where('name', $tableName)->first();
309
            $model   = $object->model;
310
            $details = $object->details;
311
            $key     = $details['findColumn'];
312
313
            if (!class_exists($model)) {
314
                return $this->generateError(["Model not found. Please create model first"]);
315
            }
316
317
            try {
318
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
319
                if ($table) {
320
                    // Remove Relationship data
321
                    foreach ($fields as $field) {
322
                        $field = json_decode($field);
323
                        $this->removeRelationshipData($field, $object, $table);
324
                    }
325
                    // Check Table deleted successfully
326
                    if ($table->delete()) {
327
                        return response()->json(['success' => true]);
328
                    }
329
                }
330
331
            } catch (\Exception $e) {
332
                return $this->generateError([$e->getMessage()]);
333
            }
334
        }
335
336
        return response()->json(['success' => false]);
337
    }
338
339
    public function getTableDetails(Request $request)
340
    {
341
        if ($request->ajax()) {
342
343
            if (($response = DBM::authorize('record.browse')) !== true) {
344
                return $response;
345
            }
346
347
            $tableName = $request->table;
348
            $object    = DBM::Object()->where('name', $tableName)->first();
349
350
            if (!$object) {
351
                return response()->json([
352
                    'success' => false,
353
                    'errors'  => ["There is no Object details"],
354
                ], 400);
355
            }
356
357
            $createFields     = $object->createFields();
358
            $browseFields     = $object->readFields();
359
            $editFields       = $object->editFields();
360
            $deleteFields     = $object->deleteFields();
361
            $fields           = $object->allFields();
362
            $foreignTableData = [];
363
364
            $createFields = $this->prepareRecordFields($createFields);
365
            $editFields   = $this->prepareRecordFields($editFields);
366
367
            $model = $object->model;
368
369
            if (!class_exists($model)) {
370
                return $this->generateError(["Model not found. Please create model first"]);
371
            }
372
373
            $perPage      = (int) $request->perPage;
374
            $query        = $request->q;
375
            $searchColumn = $object->details['searchColumn'];
376
            $records      = DBM::model($model, $tableName)->paginate($perPage);
377
378
            if (!empty($query) && !empty($searchColumn)) {
379
                $records = DBM::model($model, $tableName)
380
                    ->where($searchColumn, 'LIKE', '%' . $query . '%')
381
                    ->paginate($perPage);
382
            }
383
384
            $records       = $this->prepareRelationshipData($records, $browseFields, $object);
385
            $recordsDetail = $this->prepareJsonFieldData($records, $fields, $object, $request->findValue);
386
387
            $objectDetails            = $object->details;
388
            $objectDetails['perPage'] = $perPage;
389
390
            return response()->json([
391
                'success'          => true,
392
                'object'           => $object,
393
                'objectDetails'    => $objectDetails,
394
                'createFields'     => $createFields,
395
                'browseFields'     => $browseFields,
396
                'editFields'       => $editFields,
397
                'deleteFields'     => $deleteFields,
398
                'records'          => $recordsDetail['records'],
399
                'record'           => $recordsDetail['record'],
400
                'foreignTableData' => $foreignTableData,
401
                'userPermissions'  => DBM::userPermissions(),
402
                'pagination'       => $records,
403
            ]);
404
        }
405
406
        return response()->json(['success' => false]);
407
    }
408
409
    public function prepareRecordFields($fields)
410
    {
411
        foreach ($fields as $key => $field) {
412
413
            if ($field->type == 'relationship') {
414
415
                $relationship            = $field->settings;
416
                $foreignModel            = $relationship['foreignModel'];
417
                $foreignKey              = $relationship['foreignKey'];
418
                $fields                  = $this->removeRelationshipKeyForBelongsTo($fields, $foreignKey);
419
                $field->foreignTableData = $foreignModel::all();
420
                $field->relationship     = $relationship;
421
                continue;
422
            }
423
424
            if (isset($field->settings['options'])) {
425
                $options = $this->getSettingOptions($field);
426
                if (is_array($options)) {
427
                    $fields[$key]->options = $options;
428
                }
429
            }
430
        }
431
432
        return $fields;
433
    }
434
435
    public function prepareJsonFieldData($records, $fields, $object, $findValue)
436
    {
437
        $newRecords = [];
438
        $newRecord  = new \stdClass();
439
440
        foreach ($records as $item => $record) {
441
442
            foreach ($fields as $key => &$field) {
443
444
                if (isset($record->{$field->name})) {
445
446
                    $record->{$field->name} = is_json($record->{$field->name}) ? json_decode($record->{$field->name}, true) : $record->{$field->name};
447
                }
448
            }
449
450
            if ($findValue && $record->{$object->details['findColumn']} == $findValue) {
451
                $newRecord = $record;
452
            }
453
454
            $newRecords[] = $record;
455
        }
456
457
        return [
458
            "records" => $newRecords,
459
            "record"  => $newRecord,
460
        ];
461
    }
462
463
    public function prepareRelationshipData($records, $browseFields, $object)
464
    {
465
        foreach ($records as $item => $record) {
466
467
            foreach ($browseFields as $field) {
468
469
                if ($field->type == 'relationship') {
470
471
                    $relationship = $field->settings;
472
473
                    $findColumn = $object->details['findColumn'];
474
475
                    $localModel       = $relationship['localModel'];
476
                    $localKey         = $relationship['localKey'];
477
                    $foreignModel     = $relationship['foreignModel'];
478
                    $foreignKey       = $relationship['foreignKey'];
479
                    $relationshipType = $relationship['relationType'];
480
                    $displayLabel     = $relationship['displayLabel'];
481
482
                    if ($relationshipType == 'belongsTo') {
483
484
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
485
486
                        $datas = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->belongs_to;
487
488
                        $record->{$field->name}  = $datas;
489
                        $field->displayLabel     = $displayLabel;
490
                        $field->localKey         = $localKey;
491
                        $field->foreignKey       = $foreignKey;
492
                        $field->relationshipType = $relationshipType;
493
494
                    } else if ($relationshipType == 'hasMany') {
495
496
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
497
                        $datas       = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->has_many;
498
499
                        $record->{$field->name}  = $datas;
500
                        $field->displayLabel     = $displayLabel;
501
                        $field->localKey         = $localKey;
502
                        $field->foreignKey       = $foreignKey;
503
                        $field->relationshipType = $relationshipType;
504
505
                    } else if ($relationshipType == 'belongsToMany') {
506
507
                        $pivotTable      = $relationship['pivotTable'];
508
                        $parentPivotKey  = $relationship['parentPivotKey'];
509
                        $relatedPivotKey = $relationship['relatedPivotKey'];
510
511
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
512
513
                        $datas = DBM::Object()->setManyToManyRelation($localObject, $foreignModel, $pivotTable, $parentPivotKey, $relatedPivotKey)->belongs_to_many;
514
515
                        $record->{$field->name}  = $datas;
516
                        $field->displayLabel     = $displayLabel;
517
                        $field->localKey         = $localKey;
518
                        $field->foreignKey       = $foreignKey;
519
                        $field->relationshipType = $relationshipType;
520
                    }
521
                }
522
            }
523
        }
524
525
        return $records;
526
    }
527
}
528