Completed
Push — master ( 94fb52...42d529 )
by CodexShaper
05:02
created

RecordController::getTableDetails()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 68
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 7
eloc 47
nc 6
nop 1
dl 0
loc 68
ccs 0
cts 55
cp 0
crap 56
rs 8.223
c 4
b 0
f 0

How to fix   Long Method   

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
12
class RecordController extends Controller
13
{
14
    use RecordHelper;
0 ignored issues
show
Bug introduced by
The trait CodexShaper\DBM\Traits\RecordHelper requires the property $localTable which is not provided by CodexShaper\DBM\Http\Controllers\RecordController.
Loading history...
15
16
    public function index()
17
    {
18
        return view('dbm::app');
19
    }
20
21
    public function store(Request $request)
22
    {
23
        if ($request->ajax()) {
24
25
            if (($response = DBM::authorize('record.create')) !== true) {
26
                return $response;
27
            }
28
29
            $tableName       = $request->table;
30
            $originalColumns = Table::getColumnsName($tableName);
31
            $columns         = json_decode($request->columns);
32
            $fields          = json_decode($request->fields);
33
34
            $errors = $this->validation($fields, $columns);
35
36
            if (count($errors) > 0) {
37
                return $this->generateError($errors);
38
            }
39
40
            $object = DBM::Object()->where('name', $tableName)->first();
41
            $model  = $object->model;
42
43
            if (!class_exists($model)) {
44
                return $this->generateError(["Model not found. Please create model first"]);
45
            }
46
47
            try {
48
49
                $table = DBM::model($model, $tableName);
50
51
                foreach ($columns as $column => $value) {
52
                    if (in_array($column, $originalColumns)) {
53
54
                        if ($request->hasFile($column)) {
55
                            $value = $this->saveFiles($request, $column, $tableName);
56
                        }
57
58
                        if (!Driver::isMongoDB()) {
59
                            if ($functionName = $this->hasFunction($fields, $column)) {
60
                                $value = $this->executeFunction($functionName, $value);
61
                            }
62
                        }
63
64
                        $table->{$column} = $this->prepareStoreField($value, $tableName, $column);
65
                    }
66
                }
67
68
                if ($table->save()) {
69
                    $this->storeRelationshipData($fields, $columns, $object, $table);
70
                    return response()->json(['success' => true, 'object' => $object, 'table' => $table]);
71
                }
72
73
            } catch (\Exception $e) {
74
                return $this->generateError([$e->getMessage()]);
75
            }
76
        }
77
78
        return response()->json(['success' => false]);
79
    }
80
81
    public function update(Request $request)
82
    {
83
        if ($request->ajax()) {
84
85
            if (($response = DBM::authorize('record.update')) !== true) {
86
                return $response;
87
            }
88
89
            $tableName       = $request->table;
90
            $originalColumns = Table::getColumnsName($tableName);
91
            $columns         = json_decode($request->columns);
92
            $fields          = json_decode($request->fields);
93
94
            $errors = $this->validation($fields, $columns, 'update');
95
96
            if (count($errors) > 0) {
97
                return $this->generateError($errors);
98
            }
99
100
            $object  = DBM::Object()->where('name', $tableName)->first();
101
            $model   = $object->model;
102
            $details = $object->details;
103
            $key     = $details['findColumn'];
104
105
            if (!class_exists($model)) {
106
                return $this->generateError(["Model not found. Please create model first"]);
107
            }
108
109
            try {
110
111
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
112
113
                foreach ($columns as $column => $value) {
114
115
                    if (in_array($column, $originalColumns)) {
116
117
                        if ($request->hasFile($column)) {
118
                            $value = $this->saveFiles($request, $column, $tableName);
119
                        }
120
121
                        if ($value !== null && $value !== "") {
122
123
                            if (!Driver::isMongoDB()) {
124
                                if ($functionName = $this->hasFunction($fields, $column)) {
125
                                    $value = $this->executeFunction($functionName, $value);
126
                                }
127
                            }
128
129
                            $table->{$column} = $this->prepareStoreField($value, $tableName, $column);
130
                        }
131
                    }
132
                }
133
134
                if ($table->update()) {
135
                    $this->updateRelationshipData($fields, $columns, $object, $table);
136
                    return response()->json(['success' => true]);
137
                }
138
139
            } catch (\Exception $e) {
140
                return $this->generateError([$e->getMessage()]);
141
            }
142
        }
143
144
        return response()->json(['success' => false]);
145
    }
146
147
    public function delete(Request $request)
148
    {
149
        if ($request->ajax()) {
150
151
            if (($response = DBM::authorize('record.delete')) !== true) {
152
                return $response;
153
            }
154
155
            $tableName = $request->table;
156
            // $originalColumns = Table::getColumnsName($tableName);
157
            $columns = json_decode($request->columns);
158
            $fields  = $request->fields;
159
            $object  = DBM::Object()->where('name', $tableName)->first();
160
            $model   = $object->model;
161
            $details = $object->details;
162
            $key     = $details['findColumn'];
163
164
            if (!class_exists($model)) {
165
                return $this->generateError(["Model not found. Please create model first"]);
166
            }
167
168
            try {
169
                $table = DBM::model($model, $tableName)->where($key, $columns->{$key})->first();
170
                if ($table) {
171
                    // Remove Relationship data
172
                    foreach ($fields as $field) {
173
                        $field = json_decode($field);
174
                        $this->removeRelationshipData($field, $object, $table);
175
                    }
176
                    // Check Table deleted successfully
177
                    if ($table->delete()) {
178
                        return response()->json(['success' => true]);
179
                    }
180
                }
181
182
            } catch (\Exception $e) {
183
                return $this->generateError([$e->getMessage()]);
184
            }
185
        }
186
187
        return response()->json(['success' => false]);
188
    }
189
190
    public function getTableDetails(Request $request)
191
    {
192
        if ($request->ajax()) {
193
194
            if (($response = DBM::authorize('record.browse')) !== true) {
195
                return $response;
196
            }
197
198
            $tableName = $request->table;
199
            $object    = DBM::Object()->where('name', $tableName)->first();
200
201
            if (!$object) {
202
                return response()->json([
203
                    'success' => false,
204
                    'errors'  => ["There is no Object details"],
205
                ], 400);
206
            }
207
208
            $createFields     = $object->createFields();
209
            $browseFields     = $object->readFields();
210
            $editFields       = $object->editFields();
211
            $deleteFields     = $object->deleteFields();
212
            $fields           = $object->allFields();
213
            $foreignTableData = [];
214
215
            $createFields = $this->prepareRecordFields($createFields);
216
            $editFields   = $this->prepareRecordFields($editFields);
217
218
            $model = $object->model;
219
220
            if (!class_exists($model)) {
221
                return $this->generateError(["Model not found. Please create model first"]);
222
            }
223
224
            $perPage      = (int) $request->perPage;
225
            $query        = $request->q;
226
            $searchColumn = $object->details['searchColumn'];
227
            $records      = DBM::model($model, $tableName)->paginate($perPage);
228
229
            if (!empty($query) && !empty($searchColumn)) {
230
                $records = DBM::model($model, $tableName)
231
                    ->where($searchColumn, 'LIKE', '%' . $query . '%')
232
                    ->paginate($perPage);
233
            }
234
235
            $records       = $this->prepareRelationshipData($records, $browseFields, $object);
236
            $recordsDetail = $this->prepareJsonFieldData($records, $fields, $object, $request->findValue);
237
238
            $objectDetails            = $object->details;
239
            $objectDetails['perPage'] = $perPage;
240
241
            return response()->json([
242
                'success'          => true,
243
                'object'           => $object,
244
                'objectDetails'    => $objectDetails,
245
                'createFields'     => $createFields,
246
                'browseFields'     => $browseFields,
247
                'editFields'       => $editFields,
248
                'deleteFields'     => $deleteFields,
249
                'records'          => $recordsDetail['records'],
250
                'record'           => $recordsDetail['record'],
251
                'foreignTableData' => $foreignTableData,
252
                'userPermissions'  => DBM::userPermissions(),
253
                'pagination'       => $records,
254
            ]);
255
        }
256
257
        return response()->json(['success' => false]);
258
    }
259
260
    public function prepareRecordFields($fields)
261
    {
262
        foreach ($fields as $key => $field) {
263
264
            if ($field->type == 'relationship') {
265
266
                $relationship            = $field->settings;
267
                $foreignModel            = $relationship['foreignModel'];
268
                $foreignKey              = $relationship['foreignKey'];
269
                $fields                  = $this->removeRelationshipKeyForBelongsTo($fields, $foreignKey);
270
                $field->foreignTableData = $foreignModel::all();
271
                $field->relationship     = $relationship;
272
                continue;
273
            }
274
275
            if (isset($field->settings['options'])) {
276
                $options = $this->getSettingOptions($field);
277
                if (is_array($options)) {
278
                    $fields[$key]->options = $options;
279
                }
280
            }
281
        }
282
283
        return $fields;
284
    }
285
286
    public function prepareJsonFieldData($records, $fields, $object, $findValue)
287
    {
288
        $newRecords = [];
289
        $newRecord  = new \stdClass();
290
291
        foreach ($records as $item => $record) {
292
293
            foreach ($fields as $key => &$field) {
294
295
                if (isset($record->{$field->name})) {
296
297
                    $record->{$field->name} = is_json($record->{$field->name}) ? json_decode($record->{$field->name}, true) : $record->{$field->name};
298
                }
299
            }
300
301
            if ($findValue && $record->{$object->details['findColumn']} == $findValue) {
302
                $newRecord = $record;
303
            }
304
305
            $newRecords[] = $record;
306
        }
307
308
        return [
309
            "records" => $newRecords,
310
            "record"  => $newRecord,
311
        ];
312
    }
313
314
    public function prepareRelationshipData($records, $browseFields, $object)
315
    {
316
        foreach ($records as $item => $record) {
317
318
            foreach ($browseFields as $field) {
319
320
                if ($field->type == 'relationship') {
321
322
                    $relationship = $field->settings;
323
324
                    $findColumn = $object->details['findColumn'];
325
326
                    $localModel       = $relationship['localModel'];
327
                    $localKey         = $relationship['localKey'];
328
                    $foreignModel     = $relationship['foreignModel'];
329
                    $foreignKey       = $relationship['foreignKey'];
330
                    $relationshipType = $relationship['relationType'];
331
                    $displayLabel     = $relationship['displayLabel'];
332
333
                    if ($relationshipType == 'belongsTo') {
334
335
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
336
337
                        $datas = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->belongs_to;
338
339
                        $record->{$field->name}  = $datas;
340
                        $field->displayLabel     = $displayLabel;
341
                        $field->localKey         = $localKey;
342
                        $field->foreignKey       = $foreignKey;
343
                        $field->relationshipType = $relationshipType;
344
345
                    } else if ($relationshipType == 'hasMany') {
346
347
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
348
                        $datas       = DBM::Object()->setCommonRelation($localObject, $foreignModel, $foreignKey, $localKey)->has_many;
349
350
                        $record->{$field->name}  = $datas;
351
                        $field->displayLabel     = $displayLabel;
352
                        $field->localKey         = $localKey;
353
                        $field->foreignKey       = $foreignKey;
354
                        $field->relationshipType = $relationshipType;
355
356
                    } else if ($relationshipType == 'belongsToMany') {
357
358
                        $pivotTable      = $relationship['pivotTable'];
359
                        $parentPivotKey  = $relationship['parentPivotKey'];
360
                        $relatedPivotKey = $relationship['relatedPivotKey'];
361
362
                        $localObject = $localModel::where($findColumn, $record->{$findColumn})->first();
363
364
                        $datas = DBM::Object()->setManyToManyRelation($localObject, $foreignModel, $pivotTable, $parentPivotKey, $relatedPivotKey)->belongs_to_many;
365
366
                        $record->{$field->name}  = $datas;
367
                        $field->displayLabel     = $displayLabel;
368
                        $field->localKey         = $localKey;
369
                        $field->foreignKey       = $foreignKey;
370
                        $field->relationshipType = $relationshipType;
371
                    }
372
                }
373
            }
374
        }
375
376
        return $records;
377
    }
378
}
379