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

RecordHelper::removeRelationshipData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 42
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 30
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 42
ccs 0
cts 33
cp 0
crap 20
rs 9.44
1
<?php
2
3
namespace CodexShaper\DBM\Traits;
4
5
use CodexShaper\DBM\Facades\Manager as DBM;
6
use CodexShaper\DBM\Models\DBM_Collection;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Facades\Validator;
9
10
trait RecordHelper
11
{
12
    protected $name;
13
    protected $function_name;
14
    protected $localModel;
15
    protected $create;
16
    protected $relatedPivotKey;
17
    protected $parentPivotKey;
18
    protected $relationType;
19
    protected $details;
20
    protected $rules;
21
    protected $update;
22
    protected $type;
23
    protected $settings;
24
    protected $validation;
25
    protected $pivotTable;
26
    protected $foreignModel;
27
28
    public function saveFiles($request, $column, $tableName)
29
    {
30
        $files  = $request->file($column);
31
        $values = [];
32
        foreach ($files as $file) {
33
            $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
0 ignored issues
show
Bug introduced by
The type CodexShaper\DBM\Traits\Str 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...
34
            $path     = 'public/dbm/' . $tableName;
35
            $file->storeAs($path, $fileName);
36
            $values[] = $fileName;
37
        }
38
39
        if (count($values) > 1) {
40
            $value = $values;
41
            if (!Driver::isMongoDB()) {
0 ignored issues
show
Bug introduced by
The type CodexShaper\DBM\Traits\Driver 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...
42
                $value = json_encode($values);
43
            }
44
        } else if (count($values) == 1) {
45
            $value = $values[0];
46
        }
47
48
        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...
49
    }
50
51
    public function prepareStoreField($value, $tableName, $column)
52
    {
53
        $value = is_array($value) ? json_encode($value) : $value;
54
55
        if (Driver::isMongoDB()) {
56
57
            $fieldType = $this->getFieldType($tableName, $column);
58
59
            if (!in_array($fieldType, Type::getTypes())) {
0 ignored issues
show
Bug introduced by
The type CodexShaper\DBM\Traits\Type 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...
60
                $this->generateError([$fieldType . " type not supported."]);
61
            }
62
63
            $value = Type::$fieldType($value);
64
65
        }
66
67
        return $value;
68
    }
69
70
    public function storeRelationshipData($fields, $columns, $object, $table)
71
    {
72
        foreach ($fields as $field) {
73
74
            if (isset($field->relationship) && $field->relationship->relationType == "belongsToMany") {
75
76
                $relationship = $field->relationship;
77
78
                $localModel      = $relationship->localModel;
79
                $localTable      = $relationship->localTable;
80
                $foreignModel    = $relationship->foreignModel;
81
                $pivotTable      = $relationship->pivotTable;
82
                $parentPivotKey  = $relationship->parentPivotKey;
83
                $relatedPivotKey = $relationship->relatedPivotKey;
84
85
                $findColumn = $object->details['findColumn'];
86
87
                $localObject = DBM::model($localModel, $localTable)::where($findColumn, $table->{$findColumn})->first();
88
89
                DBM::Object()
90
                    ->setManyToManyRelation(
91
                        $localObject,
92
                        $foreignModel,
93
                        $pivotTable,
94
                        $parentPivotKey,
95
                        $relatedPivotKey
96
                    )
97
                    ->belongs_to_many()
98
                    ->attach($columns->{$relatedPivotKey});
99
            }
100
        }
101
    }
102
103
    public function updateRelationshipData($fields, $columns, $object, $table)
104
    {
105
        foreach ($fields as $field) {
106
107
            if (isset($field->relationship)) {
108
109
                $relationship = $field->relationship;
110
111
                $localModel   = $relationship->localModel;
112
                $localTable   = $relationship->localTable;
113
                $foreignModel = $relationship->foreignModel;
114
115
                if ($field->relationship->relationType == "belongsToMany") {
116
                    $pivotTable      = $relationship->pivotTable;
117
                    $parentPivotKey  = $relationship->parentPivotKey;
118
                    $relatedPivotKey = $relationship->relatedPivotKey;
119
120
                    $findColumn = $object->details['findColumn'];
121
122
                    $localObject = DBM::model($localModel, $localTable)->where($findColumn, $table->{$findColumn})->first();
123
124
                    DBM::Object()
125
                        ->setManyToManyRelation(
126
                            $localObject,
127
                            $foreignModel,
128
                            $pivotTable,
129
                            $parentPivotKey,
130
                            $relatedPivotKey
131
                        )
132
                        ->belongs_to_many()
133
                        ->sync($columns->{$relatedPivotKey});
134
                }
135
136
            }
137
        }
138
    }
139
140
    public function removeRelationshipData($field, $object, $table)
141
    {
142
        if ($field->type == 'relationship') {
143
144
            $relationship = $field->settings;
145
146
            $localModel   = $relationship->localModel;
147
            $foreignModel = $relationship->foreignModel;
148
149
            $findColumn = $object->details['findColumn'];
150
151
            $localObject = $localModel::where($findColumn, $table->{$findColumn})->first();
152
153
            if ($relationship->relationType == 'belongsToMany') {
154
155
                $pivotTable      = $relationship->pivotTable;
156
                $parentPivotKey  = $relationship->parentPivotKey;
157
                $relatedPivotKey = $relationship->relatedPivotKey;
158
159
                DBM::Object()
160
                    ->setManyToManyRelation(
161
                        $localObject,
162
                        $foreignModel,
163
                        $pivotTable,
164
                        $parentPivotKey,
165
                        $relatedPivotKey
166
                    )
167
                    ->belongs_to_many()
168
                    ->detach();
169
            } else if ($relationship->relationType == 'hasMany') {
170
171
                $foreignKey = $relationship->foreignKey;
172
                $localKey   = $relationship->localKey;
173
174
                DBM::Object()
175
                    ->setCommonRelation(
176
                        $localObject,
177
                        $foreignModel,
178
                        $foreignKey,
179
                        $localKey)
180
                    ->has_many()
181
                    ->delete();
182
            }
183
184
        }
185
    }
186
187
    public function getSettingOptions($field)
188
    {
189
        $options = $field->settings['options'];
190
        if (isset($options['controller'])) {
191
            $partials       = explode('@', $options['controller']);
192
            $controllerName = $partials[0];
193
            $methodName     = $partials[1];
194
195
            return app($controllerName)->{$methodName}();
196
        }
197
    }
198
199
    public function removeRelationshipKeyForBelongsTo($fields, $foreignKey)
200
    {
201
        $results = [];
202
203
        foreach ($fields as $key => $field) {
204
            if ($field->name == $foreignKey) {
205
                unset($fields[$key]);
206
                continue;
207
            }
208
            $results[] = $field;
209
        }
210
211
        return $results;
212
    }
213
214
    public function validation($fields, $columns, $action = "create")
215
    {
216
        $errors = [];
217
        foreach ($fields as $field) {
218
            $name = $field->name;
219
220
            if (is_object($field->settings) && property_exists($field->settings, 'validation') !== false) {
221
222
                $validationSettings = $field->settings->validation;
223
                $rules              = $this->prepareRules($columns, $action, $validationSettings);
224
                $data               = [$name => $columns->{$name}];
225
                $validator          = Validator::make($data, [$name => $rules]);
226
                if ($validator->fails()) {
227
                    foreach ($validator->errors()->all() as $error) {
228
                        $errors[] = $error;
229
                    }
230
                }
231
            }
232
        }
233
234
        return $errors;
235
    }
236
237
    public function prepareRules($columns, $action, $settings)
238
    {
239
        $rules = '';
240
241
        if (is_string($settings)) {
242
            $rules = $settings;
243
        } else if ($action == 'create' && isset($settings->create)) {
244
            $createSettings = $settings->create;
245
            $rules          = $createSettings->rules;
246
        } else if ($action == 'update' && isset($settings->update)) {
247
            $updateSettings = $settings->update;
248
            $localKey       = $updateSettings->localKey;
249
            $rules          = $updateSettings->rules . ',' . $columns->{$localKey};
250
        }
251
252
        return $rules;
253
    }
254
255
    public function getFieldType($collectionName, $fieldName)
256
    {
257
        $collection = DBM_Collection::where('name', $collectionName)->first();
258
259
        return $collection->fields()->where('name', $fieldName)->first()->type;
260
    }
261
262
    public function generateError($errors)
263
    {
264
        return response()->json([
265
            'success' => false,
266
            'errors'  => $errors,
267
        ], 400);
268
    }
269
270
    public function hasFunction($fields, $column)
271
    {
272
        foreach ($fields as $field) {
273
            if ($field->name == $column && ($field->function_name != null || $field->function_name != "")) {
274
                return $field->function_name;
275
            }
276
        }
277
278
        return false;
279
    }
280
281
    public function executeFunction($functionName, $value = null)
282
    {
283
        $signature = ($value != null) ? "{$functionName}('{$value}')" : "{$functionName}()";
284
285
        $result = DB::raw("{$signature}");
286
287
        return $result;
288
    }
289
}
290