Completed
Push — master ( 129670...806d76 )
by CodexShaper
05:18
created

RecordTrait::prepareRules()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 7
eloc 13
c 2
b 0
f 1
nc 5
nop 3
dl 0
loc 19
ccs 0
cts 17
cp 0
crap 56
rs 8.8333
1
<?php
2
3
namespace CodexShaper\DBM\Traits;
4
5
use CodexShaper\DBM\Database\Drivers\MongoDB\Type;
6
use CodexShaper\DBM\Facades\Driver;
7
use CodexShaper\DBM\Facades\Manager as DBM;
8
use CodexShaper\DBM\Models\DBM_Collection;
9
use Illuminate\Support\Facades\DB;
10
use Illuminate\Support\Facades\Validator;
11
use Illuminate\Support\Str;
12
13
trait RecordTrait
14
{
15
    protected $name;
16
    protected $function_name;
17
    protected $localModel;
18
    protected $create;
19
    protected $relatedPivotKey;
20
    protected $parentPivotKey;
21
    protected $relationType;
22
    protected $details;
23
    protected $rules;
24
    protected $update;
25
    protected $type;
26
    protected $settings;
27
    protected $validation;
28
    protected $pivotTable;
29
    protected $foreignModel;
30
    protected $localTable;
31
32
    /**
33
     * Store files in storage
34
     *
35
     * @param \Illuminate\Http\Request $request
36
     * @param string $column
37
     * @param string $tableName
38
     *
39
     * @return array|string
40
     */
41
    public function saveFiles($request, $column, $tableName)
42
    {
43
        $files  = $request->file($column);
44
        $values = [];
45
        foreach ($files as $file) {
46
            $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
47
            $path     = trim(config('dbm.filesystem.dir'), '/') . DIRECTORY_SEPARATOR . $tableName;
48
            $file->storeAs($path, $fileName);
49
            $values[] = $fileName;
50
        }
51
52
        if (count($values) > 1) {
53
            $value = $values;
54
            if (!Driver::isMongoDB()) {
55
                $value = json_encode($values);
56
            }
57
        } else if (count($values) == 1) {
58
            $value = $values[0];
59
        }
60
61
        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...
62
    }
63
    /**
64
     * Prepare fields to store
65
     *
66
     * @param array|string|int|double|bool $request
67
     * @param string $tableName
68
     * @param string $column
69
     *
70
     * @return array|string|int|double|bool
71
     */
72
    public function prepareStoreField($value, $tableName, $column)
73
    {
74
        $value = is_array($value) ? json_encode($value) : $value;
75
76
        if (Driver::isMongoDB()) {
77
78
            $fieldType = $this->getFieldType($tableName, $column);
79
80
            if (!in_array($fieldType, Type::getTypes())) {
81
                $this->generateError([$fieldType . " type not supported."]);
82
            }
83
84
            if ($fieldType != 'timestamp') {
85
                $value = Type::$fieldType($value);
86
            }
87
88
        }
89
90
        return $value;
91
    }
92
    /**
93
     * Prepare record fields
94
     *
95
     * @param \Illuminate\Support\Collection $fields
96
     *
97
     * @return \Illuminate\Support\Collection
98
     */
99
    public function prepareRecordFields($fields)
100
    {
101
        foreach ($fields as $key => $field) {
102
103
            if ($field->type == 'relationship') {
104
105
                $relationship            = $field->settings;
106
                $foreignModel            = $relationship['foreignModel'];
107
                $foreignKey              = $relationship['foreignKey'];
108
                $fields                  = $this->removeRelationshipKeyForBelongsTo($fields, $foreignKey);
109
                $field->foreignTableData = $foreignModel::all();
110
                $field->relationship     = $relationship;
111
                continue;
112
            }
113
114
            if (isset($field->settings['options'])) {
115
                $options = $this->getSettingOptions($field);
116
                if (is_array($options)) {
117
                    $fields[$key]->options = $options;
118
                }
119
            }
120
        }
121
122
        return $fields;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $fields also could return the type array which is incompatible with the documented return type Illuminate\Support\Collection.
Loading history...
123
    }
124
    /**
125
     * Remove field when belongs_to relation
126
     *
127
     * @param \Illuminate\Support\Collection $fields
128
     * @param string $foreignKey
129
     *
130
     * @return array
131
     */
132
    public function removeRelationshipKeyForBelongsTo($fields, $foreignKey)
133
    {
134
        $results = [];
135
136
        foreach ($fields as $key => $field) {
137
            if ($field->name == $foreignKey) {
138
                unset($fields[$key]);
139
                continue;
140
            }
141
            $results[] = $field;
142
        }
143
144
        return $results;
145
    }
146
    /**
147
     * Prepare Record Details
148
     *
149
     * @param mixed $records
150
     * @param \Illuminate\Support\Collection $fields
151
     * @param \CodexShaper\DBM\Models\DBM_Object|\CodexShaper\DBM\Models\DBM_MongoObject $object
152
     * @param string $findValue
153
     *
154
     * @return array
155
     */
156
    public function prepareRecordDetails($records, $fields, $object, $findValue)
157
    {
158
        $newRecords = [];
159
        $newRecord  = new \stdClass();
160
161
        foreach ($records as $item => $record) {
162
163
            foreach ($fields as $key => &$field) {
164
165
                if (isset($record->{$field->name})) {
166
167
                    $record->{$field->name} = is_json($record->{$field->name}) ? json_decode($record->{$field->name}, true) : $record->{$field->name};
168
                }
169
            }
170
171
            if ($findValue && $record->{$object->details['findColumn']} == $findValue) {
172
                $newRecord = $record;
173
            }
174
175
            $newRecords[] = $record;
176
        }
177
178
        return [
179
            "records" => $newRecords,
180
            "record"  => $newRecord,
181
        ];
182
    }
183
    /**
184
     * Get options for Dropdown, Selectbox, Radio button and other fields via controller
185
     *
186
     * @param object $field
187
     *
188
     * @return array|mixed
189
     */
190
    public function getSettingOptions($field)
191
    {
192
        $options = $field->settings['options'];
193
        if (isset($options['controller'])) {
194
            $partials       = explode('@', $options['controller']);
195
            $controllerName = $partials[0];
196
            $methodName     = $partials[1];
197
198
            return app($controllerName)->{$methodName}();
199
        }
200
    }
201
    /**
202
     * Check validation and return errors if fails
203
     *
204
     * @param array $fields
205
     * @param object $columns
206
     * @param string $action
207
     *
208
     * @return array
209
     */
210
    public function validation($fields, $columns, $action = "create")
211
    {
212
        $errors = [];
213
        foreach ($fields as $field) {
214
            $name = $field->name;
215
216
            if (is_object($field->settings) && property_exists($field->settings, 'validation') !== false) {
217
218
                $validationSettings = $field->settings->validation;
219
                $rules              = $this->prepareRules($columns, $action, $validationSettings);
220
                $data               = [$name => $columns->{$name}];
221
                $validator          = Validator::make($data, [$name => $rules]);
222
                if ($validator->fails()) {
223
                    foreach ($validator->errors()->all() as $error) {
224
                        $errors[] = $error;
225
                    }
226
                }
227
            }
228
        }
229
230
        return $errors;
231
    }
232
    /**
233
     * Prepare validation rules
234
     *
235
     * @param object $columns
236
     * @param string $action
237
     * @param string|object $settings
238
     *
239
     * @return array|string
240
     */
241
    public function prepareRules($columns, $action, $settings)
242
    {
243
        $rules = '';
244
245
        if (is_string($settings)) {
246
            $rules = $settings;
247
        } else if ($action == 'create' && isset($settings->create)) {
248
            $createSettings = $settings->create;
249
            $rules          = $createSettings->rules;
250
        } else if ($action == 'update' && isset($settings->update)) {
251
            $updateSettings = $settings->update;
252
            $rules          = $updateSettings->rules;
253
            if (isset($updateSettings->localKey)) {
254
                $localKey = $updateSettings->localKey;
255
                $rules    = $updateSettings->rules . ',' . $columns->{$localKey};
256
            }
257
        }
258
259
        return $rules;
260
    }
261
    /**
262
     * Get field name
263
     *
264
     * @param string $collectionName
265
     * @param string $fieldName
266
     *
267
     * @return string
268
     */
269
    public function getFieldType($collectionName, $fieldName)
270
    {
271
        $collection = DBM_Collection::where('name', $collectionName)->first();
272
273
        return $collection->fields()->where('name', $fieldName)->first()->type;
274
    }
275
    /**
276
     * Generate errors and return response
277
     *
278
     * @param array $errors
279
     *
280
     * @return \Illuminate\Http\JsonResponse
281
     */
282
    public function generateError($errors)
283
    {
284
        return response()->json([
285
            'success' => false,
286
            'errors'  => $errors,
287
        ], 400);
288
    }
289
    /**
290
     * Check Function name is available for MySQL
291
     *
292
     * @param array $fields
293
     * @param string $column
294
     *
295
     * @return string|false
296
     */
297
    public function hasFunction($fields, $column)
298
    {
299
        foreach ($fields as $field) {
300
            if ($field->name == $column && ($field->function_name != null || $field->function_name != "")) {
301
                return $field->function_name;
302
            }
303
        }
304
305
        return false;
306
    }
307
    /**
308
     * Execute MySQL Function
309
     *
310
     * @param string $functionName
311
     * @param string|int|double|bool|null $column
312
     *
313
     * @return string|int|double|bool
314
     */
315
    public function executeFunction($functionName, $value = null)
316
    {
317
        $signature = ($value != null) ? "{$functionName}('{$value}')" : "{$functionName}()";
318
        $result    = DB::raw("{$signature}");
319
        return $result;
320
    }
321
}
322