Passed
Push — master ( bcbfaf...ef244f )
by CodexShaper
04:47
created

RecordTrait::hasFunction()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 4
nc 3
nop 2
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 30
rs 9.6111
c 0
b 0
f 0
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
    public function saveFiles($request, $column, $tableName)
33
    {
34
        $files  = $request->file($column);
35
        $values = [];
36
        foreach ($files as $file) {
37
            $fileName = Str::random(config('dbm.filesystem.random_length')) . '.' . $file->getClientOriginalExtension();
38
            $path     = 'public/dbm/' . $tableName;
39
            $file->storeAs($path, $fileName);
40
            $values[] = $fileName;
41
        }
42
43
        if (count($values) > 1) {
44
            $value = $values;
45
            if (!Driver::isMongoDB()) {
46
                $value = json_encode($values);
47
            }
48
        } else if (count($values) == 1) {
49
            $value = $values[0];
50
        }
51
52
        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...
53
    }
54
55
    public function prepareStoreField($value, $tableName, $column)
56
    {
57
        $value = is_array($value) ? json_encode($value) : $value;
58
59
        if (Driver::isMongoDB()) {
60
61
            $fieldType = $this->getFieldType($tableName, $column);
62
63
            if (!in_array($fieldType, Type::getTypes())) {
64
                $this->generateError([$fieldType . " type not supported."]);
65
            }
66
67
            $value = Type::$fieldType($value);
68
69
        }
70
71
        return $value;
72
    }
73
74
    public function prepareRecordFields($fields)
75
    {
76
        foreach ($fields as $key => $field) {
77
78
            if ($field->type == 'relationship') {
79
80
                $relationship            = $field->settings;
81
                $foreignModel            = $relationship['foreignModel'];
82
                $foreignKey              = $relationship['foreignKey'];
83
                $fields                  = $this->removeRelationshipKeyForBelongsTo($fields, $foreignKey);
0 ignored issues
show
Bug introduced by
It seems like removeRelationshipKeyForBelongsTo() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

83
                /** @scrutinizer ignore-call */ 
84
                $fields                  = $this->removeRelationshipKeyForBelongsTo($fields, $foreignKey);
Loading history...
84
                $field->foreignTableData = $foreignModel::all();
85
                $field->relationship     = $relationship;
86
                continue;
87
            }
88
89
            if (isset($field->settings['options'])) {
90
                $options = $this->getSettingOptions($field);
91
                if (is_array($options)) {
92
                    $fields[$key]->options = $options;
93
                }
94
            }
95
        }
96
97
        return $fields;
98
    }
99
100
    public function prepareJsonFieldData($records, $fields, $object, $findValue)
101
    {
102
        $newRecords = [];
103
        $newRecord  = new \stdClass();
104
105
        foreach ($records as $item => $record) {
106
107
            foreach ($fields as $key => &$field) {
108
109
                if (isset($record->{$field->name})) {
110
111
                    $record->{$field->name} = is_json($record->{$field->name}) ? json_decode($record->{$field->name}, true) : $record->{$field->name};
112
                }
113
            }
114
115
            if ($findValue && $record->{$object->details['findColumn']} == $findValue) {
116
                $newRecord = $record;
117
            }
118
119
            $newRecords[] = $record;
120
        }
121
122
        return [
123
            "records" => $newRecords,
124
            "record"  => $newRecord,
125
        ];
126
    }
127
128
    public function getSettingOptions($field)
129
    {
130
        $options = $field->settings['options'];
131
        if (isset($options['controller'])) {
132
            $partials       = explode('@', $options['controller']);
133
            $controllerName = $partials[0];
134
            $methodName     = $partials[1];
135
136
            return app($controllerName)->{$methodName}();
137
        }
138
    }
139
140
    public function validation($fields, $columns, $action = "create")
141
    {
142
        $errors = [];
143
        foreach ($fields as $field) {
144
            $name = $field->name;
145
146
            if (is_object($field->settings) && property_exists($field->settings, 'validation') !== false) {
147
148
                $validationSettings = $field->settings->validation;
149
                $rules              = $this->prepareRules($columns, $action, $validationSettings);
150
                $data               = [$name => $columns->{$name}];
151
                $validator          = Validator::make($data, [$name => $rules]);
152
                if ($validator->fails()) {
153
                    foreach ($validator->errors()->all() as $error) {
154
                        $errors[] = $error;
155
                    }
156
                }
157
            }
158
        }
159
160
        return $errors;
161
    }
162
163
    public function prepareRules($columns, $action, $settings)
164
    {
165
        $rules = '';
166
167
        if (is_string($settings)) {
168
            $rules = $settings;
169
        } else if ($action == 'create' && isset($settings->create)) {
170
            $createSettings = $settings->create;
171
            $rules          = $createSettings->rules;
172
        } else if ($action == 'update' && isset($settings->update)) {
173
            $updateSettings = $settings->update;
174
            $localKey       = $updateSettings->localKey;
175
            $rules          = $updateSettings->rules . ',' . $columns->{$localKey};
176
        }
177
178
        return $rules;
179
    }
180
181
    public function getFieldType($collectionName, $fieldName)
182
    {
183
        $collection = DBM_Collection::where('name', $collectionName)->first();
184
185
        return $collection->fields()->where('name', $fieldName)->first()->type;
186
    }
187
188
    public function generateError($errors)
189
    {
190
        return response()->json([
191
            'success' => false,
192
            'errors'  => $errors,
193
        ], 400);
194
    }
195
196
    public function hasFunction($fields, $column)
197
    {
198
        foreach ($fields as $field) {
199
            if ($field->name == $column && ($field->function_name != null || $field->function_name != "")) {
200
                return $field->function_name;
201
            }
202
        }
203
204
        return false;
205
    }
206
207
    public function executeFunction($functionName, $value = null)
208
    {
209
        $signature = ($value != null) ? "{$functionName}('{$value}')" : "{$functionName}()";
210
211
        $result = DB::raw("{$signature}");
212
213
        return $result;
214
    }
215
}
216