Completed
Push — master ( fdb9c9...524f9b )
by CodexShaper
04:20
created

RelationController::add()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 20
c 2
b 0
f 0
nc 5
nop 1
dl 0
loc 34
ccs 0
cts 26
cp 0
crap 30
rs 9.2888
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 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...
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Str;
11
12
class RelationController extends Controller
13
{
14
    public function get(Request $request)
15
    {
16
        if ($request->ajax()) {
17
18
            if (($response = DBM::authorize('relationship.update')) !== true) {
19
                return $response;
20
            }
21
22
            $tableName = $request->table;
23
            $object    = DBM::Object()->where('name', $tableName)->first();
24
            $fields    = $object->fields;
25
            $field     = $this->prepareRelationshipField($fields, json_decode($request->field));
26
27
            return response()->json(['success' => true, 'field' => $field]);
28
        }
29
30
        return response()->json(['success' => false]);
31
    }
32
33
    public function prepareRelationshipField($fields, $field)
34
    {
35
        $prefix = (Driver::isMongoDB()) ? "_" : "";
36
37
        foreach ($fields as $fld) {
38
            if ($fld->id == $field->{$prefix . "id"}) {
39
40
                $relationship = $fld->settings;
41
                $localTable   = $relationship['localTable'];
42
                $foreignTable = $relationship['foreignTable'];
43
                $pivotTable   = $relationship['pivotTable'];
44
45
                $field->localFields   = Table::getTable($localTable);
46
                $field->foreignFields = Table::getTable($foreignTable);
47
                $field->pivotFields   = Table::getTable($pivotTable);
48
                $field->relationship  = $relationship;
49
            }
50
        }
51
52
        return $field;
53
    }
54
55
    public function add(Request $request)
56
    {
57
        if ($request->ajax()) {
58
59
            if (($response = DBM::authorize('relationship.create')) !== true) {
60
                return $response;
61
            }
62
63
            $relationship = $request->relationship;
64
65
            if (($response = $this->checkErrors($relationship)) !== true) {
66
                return $response;
67
            }
68
69
            $fieldName = $this->getFieldName($relationship);
70
            $settings  = $this->prepareSettings($relationship);
71
72
            $object = DBM::Object()->where('name', $relationship['localTable'])->first();
73
            $order  = DBM::Field()->where('dbm_object_id', $object->id)->max('order');
74
75
            $field                = DBM::Field();
76
            $field->dbm_object_id = $object->id;
77
            $field->name          = $fieldName;
78
            $field->type          = 'relationship';
79
            $field->display_name  = ucfirst($relationship['foreignTable']);
80
            $field->order         = $order + 1;
81
            $field->settings      = $settings;
82
83
            if ($field->save()) {
84
                return response()->json(['success' => true]);
85
            }
86
        }
87
88
        return response()->json(['success' => false]);
89
    }
90
91
    public function checkErrors($relationship)
92
    {
93
        $localModel   = $relationship['localModel'];
94
        $foreignModel = $relationship['foreignModel'];
95
96
        if (!class_exists($localModel)) {
97
            $error = "{$localModel} Model not found. Please create the {$localModel} model first";
98
            return $this->generateError([$error]);
99
        }
100
101
        if (!class_exists($foreignModel)) {
102
            $error = "{$foreignModel} Model not found. Please create the {$foreignModel} model first";
103
            return $this->generateError([$error]);
104
        }
105
106
        return true;
107
    }
108
109
    public function getFieldName($relationship)
110
    {
111
        $localTable   = Str::singular($relationship['localTable']);
112
        $foreignTable = Str::singular($relationship['foreignTable']);
113
        $relationType = $relationship['type'];
114
115
        return strtolower("{$localTable}_{$relationType}_{$foreignTable}_relationship");
116
    }
117
118
    public function prepareSettings($relationship)
119
    {
120
        return [
121
            'relationType'    => $relationship['type'],
122
            'localModel'      => $relationship['localModel'],
123
            'localTable'      => $relationship['localTable'],
124
            'localKey'        => $relationship['localKey'],
125
            'foreignModel'    => $relationship['foreignModel'],
126
            'foreignTable'    => $relationship['foreignTable'],
127
            'foreignKey'      => $relationship['foreignKey'],
128
            'displayLabel'    => $relationship['displayLabel'],
129
            'pivotTable'      => $relationship['pivotTable'],
130
            'parentPivotKey'  => $relationship['parentPivotKey'],
131
            'relatedPivotKey' => $relationship['relatedPivotKey'],
132
        ];
133
    }
134
135
    public function update(Request $request)
136
    {
137
        if ($request->ajax()) {
138
139
            if (($response = DBM::authorize('relationship.update')) !== true) {
140
                return $response;
141
            }
142
143
            $relationship = $request->relationship;
144
            $field        = $request->field;
145
146
            $settings = $this->prepareSettings($relationship);
147
148
            $field           = DBM::Field()::find($field['id']);
149
            $field->settings = $settings;
150
            if ($field->update()) {
151
                return response()->json(['success' => true]);
152
            }
153
        }
154
155
        return response()->json(['success' => false]);
156
    }
157
158
    public function delete(Request $request)
159
    {
160
        if ($request->ajax()) {
161
162
            if (($response = DBM::authorize('relationship.delete')) !== true) {
163
                return $response;
164
            }
165
166
            $tableName = $request->table;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableName is dead and can be removed.
Loading history...
167
            $data      = json_decode($request->field);
168
169
            $field = DBM::Field()::find($data->id);
170
171
            if ($field->delete()) {
172
                return response()->json(['success' => true]);
173
            }
174
        }
175
176
        return response()->json(['success' => false]);
177
    }
178
179
    protected function generateError($errors)
180
    {
181
        return response()->json([
182
            'success' => false,
183
            'errors'  => $errors,
184
        ], 400);
185
    }
186
}
187