Completed
Push — master ( 6ee823...14bb9c )
by CodexShaper
04:29
created

DatabaseController::getTableColumns()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 15
ccs 0
cts 11
cp 0
crap 12
rs 10
1
<?php
2
3
namespace CodexShaper\DBM\Http\Controllers;
4
5
use CodexShaper\DBM\Database\Schema\Table;
6
use CodexShaper\DBM\Facades\Driver;
7
use CodexShaper\DBM\Facades\Manager as DBM;
8
use CodexShaper\DBM\Models\CollectionField;
9
use CodexShaper\DBM\Models\DBM_Collection;
10
use Illuminate\Http\Request;
11
use Illuminate\Support\Str;
12
13
class DatabaseController extends Controller
14
{
15
16
    public function index()
17
    {
18
        return view('dbm::app');
19
    }
20
21
    public function create(Request $request)
22
    {
23
        if ($request->ajax()) {
24
25
            $table = json_decode($request->table, true);
26
27
            if (($response = DBM::authorize('database.create')) !== true) {
28
                return $response;
29
            }
30
31
            try
32
            {
33
                Table::create($request->table);
34
35
                if (Driver::isMongoDB()) {
36
                    $collection           = new DBM_Collection;
37
                    $collection->name     = $table['name'];
38
                    $collection->old_name = $table['name'];
39
                    $collection->extra    = [];
40
41
                    if ($collection->save()) {
42
                        $id = $collection->_id;
43
44
                        $collection_field = new CollectionField;
45
46
                        $collection_field->dbm_collection_id = $id;
47
                        $collection_field->name              = '_id';
48
                        $collection_field->old_name          = '_id';
49
                        $collection_field->type              = 'ObjectId';
50
                        $collection_field->index             = 'PRIMARY_KEY';
51
                        $collection_field->extra             = [];
52
53
                        $collection_field->save();
54
                    }
55
                }
56
                return response()->json(['success' => true]);
57
            } catch (\Exception $e) {
58
                return response()->json([
59
                    'success' => false,
60
                    'errors'  => [$e->getMessage()],
61
                ], 400);
62
            }
63
        }
64
65
        return response()->json(['success' => false]);
66
    }
67
68
    public function updateMongoDbTable($table)
69
    {
70
        $tableName = $table['oldName'];
71
        $newName   = $table['name'];
72
        $columns   = $table['columns'];
73
74
        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
75
            if ($tableName != $newName) {
76
                $collection->name     = $newName;
77
                $collection->old_name = $newName;
78
                $collection->update();
79
            }
80
        } else {
81
            $collection           = new DBM_Collection;
82
            $collection->name     = $newName;
83
            $collection->old_name = $newName;
84
            $collection->save();
85
        }
86
87
        if ($collection) {
88
89
            $id         = $collection->_id;
90
            $fieldNames = (!empty($collection->fields)) ? $collection->fields->pluck('old_name')->toArray() : [];
91
92
            foreach ($columns as $column) {
93
94
                if (in_array($column['oldName'], $fieldNames)) {
95
96
                    $collection_field = CollectionField::where('old_name', $column['oldName'])->first();
97
98
                    $collection_field->name     = $column['name'];
99
                    $collection_field->old_name = $column['oldName'];
100
                    $collection_field->type     = $column['type']['name'];
101
                    $collection_field->update();
102
                    $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
103
                } else {
104
105
                    $collection_field = new CollectionField;
106
107
                    $collection_field->dbm_collection_id = $id;
108
                    $collection_field->name              = $column['name'];
109
                    $collection_field->old_name          = $column['name'];
110
                    $collection_field->type              = $column['type']['name'];
111
                    $collection_field->index             = '';
112
                    $collection_field->extra             = [];
113
114
                    $collection_field->save();
115
                }
116
            }
117
118
            if (count($fieldNames) > 0) {
119
                foreach ($fieldNames as $fieldName) {
120
                    $field = CollectionField::where([
121
                        'dbm_collection_id' => $id,
122
                        'name'              => $fieldName])->first();
123
                    $field->delete();
124
                }
125
            }
126
127
        }
128
    }
129
130
    public function addOrUpdateCrudField($object, $column, &$fieldNames)
131
    {
132
        $columnType = $column['type'];
133
134
        if (in_array($column['oldName'], $fieldNames)) {
135
136
            $field = DBM::Field()->where([
137
                'dbm_object_id' => $object->id,
138
                'name'          => $column['oldName'],
139
            ])->first();
140
141
            $field->name = $column['name'];
142
            if ($column['oldName'] != $column['name']) {
143
                $field->display_name = ucfirst($column['name']);
144
            }
145
            $field->order = $column['order'];
146
            $field->update();
147
148
            $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
149
        } else {
150
151
            if (DBM::Field()->where([
152
                'dbm_object_id' => $object->id,
153
                'name'          => $column['name']])->first()) {
154
                return response()->json([
155
                    'success' => false,
156
                    'errors'  => ["Field name must be unique. " . $column['name'] . " are duplicate"],
157
                ], 400);
158
            }
159
160
            $field                = DBM::Field();
161
            $field->dbm_object_id = $object->id;
162
            $field->name          = $column['name'];
163
            $field->display_name  = ucfirst($column['name']);
164
            $field->type          = static::getInputType($columnType['name']);
165
            $field->order         = $column['order'];
166
167
            if ($column['autoincrement'] == true) {
168
                $field->create = false;
169
                $field->read   = false;
170
                $field->edit   = false;
171
                $field->delete = false;
172
            }
173
174
            $field->save();
175
        }
176
    }
177
178
    public function updateCrudFields($table)
179
    {
180
        $tableName = $table['oldName'];
181
        $newName   = $table['name'];
182
        $columns   = $table['columns'];
183
184
        if ($tableName != $newName) {
185
186
            DBM::Object()->where('slug', Str::slug($tableName))->update([
187
                'name'         => $newName,
188
                'slug'         => Str::slug($newName),
189
                'display_name' => ucfirst($newName),
190
            ]);
191
192
            $tableName = $newName;
193
        }
194
195
        if ($object = DBM::Object()::where('slug', Str::slug($tableName))->first()) {
196
197
            $fieldNames = $object->fields->pluck('name')->toArray();
0 ignored issues
show
Bug introduced by
The method pluck() does not exist on null. ( Ignorable by Annotation )

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

197
            $fieldNames = $object->fields->/** @scrutinizer ignore-call */ pluck('name')->toArray();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
198
            // $relationshipItems = [];
199
200
            foreach ($columns as $column) {
201
202
                $this->addOrUpdateCrudField($object, $column, $fieldNames);
203
204
            }
205
206
            if (count($fieldNames) > 0) {
207
                foreach ($fieldNames as $fieldName) {
208
                    $field = DBM::Field()->where([
209
                        'dbm_object_id' => $object->id,
210
                        'name'          => $fieldName])->first();
211
                    if ($field->type != 'relationship') {
212
                        $field->delete();
213
                    }
214
                }
215
            }
216
        }
217
    }
218
219
    public function update(Request $request)
220
    {
221
        if ($request->ajax()) {
222
223
            if (($response = DBM::authorize('database.update')) !== true) {
224
                return $response;
225
            }
226
227
            $table = $request->table;
228
229
            if (!is_array($table)) {
230
                $table = json_decode($table, true);
231
            }
232
233
            $tableName = $table['oldName'];
234
235
            try
236
            {
237
                // Update Template
238
                (new \CodexShaper\DBM\Http\Controllers\TemplateController)->updateTemplates($request);
239
240
                if (Table::exists($tableName)) {
241
242
                    if (Driver::isMongoDB()) {
243
244
                        $this->updateMongoDbTable($table);
245
                    }
246
247
                    // Update Database
248
                    Table::update($request->table);
249
250
                    // Update Crud fields
251
                    $this->updateCrudFields($table);
252
253
                    return response()->json(['success' => true]);
254
                }
255
256
            } catch (\Exception $e) {
257
258
                return response()->json([
259
                    'success' => false,
260
                    'errors'  => [$e->getMessage()],
261
                ], 400);
262
            }
263
        }
264
265
        return response()->json(['success' => false]);
266
267
    }
268
269
    public function delete(Request $request)
270
    {
271
        if ($request->ajax()) {
272
273
            if (($response = DBM::authorize('database.delete')) !== true) {
274
                return $response;
275
            }
276
277
            $tableName = $request->table;
278
279
            try
280
            {
281
                if (Table::exists($tableName)) {
282
283
                    if (Driver::isMongoDB()) {
284
                        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
285
                            $collection->fields()->delete();
286
                            $collection->delete();
287
                        }
288
                    }
289
290
                    if ($object = DBM::Object()->where('slug', Str::slug($tableName))->first()) {
291
292
                        $object->fields()->delete();
293
                        $object->delete();
294
                    }
295
296
                    Table::drop($tableName);
297
298
                    return response()->json(['success' => true]);
299
                }
300
301
            } catch (\Exception $e) {
302
303
                return response()->json([
304
                    'success' => false,
305
                    'errors'  => [$e->getMessage()],
306
                ], 400);
307
            }
308
        }
309
310
        return response()->json(['success' => false]);
311
    }
312
313
    public static function getInputType($name)
314
    {
315
        $types = static::inputTypes();
316
        foreach ($types as $type => $value) {
317
            if (in_array($name, $value)) {
318
                return $type;
319
            }
320
        }
321
        return 'text';
322
    }
323
324
    public static function inputTypes()
325
    {
326
        return [
327
            'number'    => [
328
                'tinyint',
329
                'smallint',
330
                'mediumint',
331
                'integer',
332
                'int',
333
                'bigint',
334
                'decimal',
335
                'numeric',
336
            ],
337
            'text'      => [
338
                'money',
339
                'float',
340
                'real',
341
                'double',
342
                'double precision',
343
                // String
344
                'char',
345
                'character',
346
                'varchar',
347
                'character varying',
348
                'string',
349
                'guid',
350
                'uuid',
351
                // Lists
352
                'json',
353
                'jsonb',
354
                'json_array',
355
            ],
356
            'password'  => [
357
                'password',
358
            ],
359
            'email'     => [],
360
            'select'    => [],
361
            'radio'     => [],
362
            'checkbox'  => [
363
                'boolean',
364
            ],
365
            'textarea'  => [
366
                'tinytext',
367
                'text',
368
                'mediumtext',
369
                'longtext',
370
                'tsquery',
371
                'tsvector',
372
                'xml',
373
            ],
374
            'date'      => [
375
                'date',
376
                'datetime',
377
                'year',
378
                'timetz',
379
                'timestamptz',
380
                'datetimetz',
381
                'dateinterval',
382
                'interval',
383
            ],
384
            'timestamp' => [
385
                'timestamp',
386
            ],
387
            'color'     => [],
388
            'file'      => [],
389
            'image'     => [],
390
            'hidden'    => [],
391
            'month'     => [],
392
            'week'      => [],
393
            'time'      => [
394
                'time',
395
            ],
396
            'url'       => [],
397
            'tel'       => [],
398
            'submit'    => [],
399
            'search'    => [],
400
        ];
401
    }
402
403
}
404