Issues (124)

src/Http/Controllers/DatabaseController.php (4 issues)

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
     * Load all database tables.
17
     *
18
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
19
     */
20
    public function index()
21
    {
22
        return view('dbm::app');
23
    }
24
25
    /**
26
     * Create CRUD.
27
     *
28
     * @return \Illuminate\Http\JsonResponse
29
     */
30
    public function create(Request $request)
31
    {
32
        if ($request->ajax()) {
33
            $table = json_decode($request->table, true);
34
35
            if (($response = DBM::authorize('database.create')) !== true) {
0 ignored issues
show
The condition $response = CodexShaper\...abase.create') !== true is always true.
Loading history...
36
                return $response;
37
            }
38
39
            try {
40
                Table::create($request->table);
41
42
                if (Driver::isMongoDB()) {
43
                    $collection = new DBM_Collection;
44
                    $collection->name = $table['name'];
45
                    $collection->old_name = $table['name'];
46
                    $collection->extra = [];
47
48
                    if ($collection->save()) {
49
                        $id = $collection->_id;
50
51
                        $collection_field = new CollectionField;
52
53
                        $collection_field->dbm_collection_id = $id;
54
                        $collection_field->name = '_id';
55
                        $collection_field->old_name = '_id';
56
                        $collection_field->type = 'ObjectId';
57
                        $collection_field->index = 'PRIMARY_KEY';
58
                        $collection_field->extra = [];
59
60
                        $collection_field->save();
61
                    }
62
                }
63
64
                return response()->json(['success' => true]);
65
            } catch (\Exception $e) {
66
                return response()->json([
67
                    'success' => false,
68
                    'errors' => [$e->getMessage()],
69
                ], 400);
70
            }
71
        }
72
73
        return response()->json(['success' => false]);
74
    }
75
76
    /**
77
     * Update MongoDB Collection.
78
     *
79
     * @param array $table
80
     *
81
     * @return void
82
     */
83
    public function updateMongoDbTable($table)
84
    {
85
        $tableName = $table['oldName'];
86
        $newName = $table['name'];
87
        $columns = $table['columns'];
88
89
        if ($collection = DBM_Collection::where('name', $tableName)->first()) {
90
            if ($tableName != $newName) {
91
                $collection->name = $newName;
92
                $collection->old_name = $newName;
93
                $collection->update();
94
            }
95
        } else {
96
            $collection = new DBM_Collection;
97
            $collection->name = $newName;
98
            $collection->old_name = $newName;
99
            $collection->save();
100
        }
101
102
        if ($collection) {
103
            $id = $collection->_id;
104
            $fieldNames = (! empty($collection->fields)) ? $collection->fields->pluck('old_name')->toArray() : [];
105
106
            foreach ($columns as $column) {
107
                if (in_array($column['oldName'], $fieldNames)) {
108
                    $collection_field = CollectionField::where([
109
                        'dbm_collection_id' => $collection->_id,
110
                        'old_name' => $column['oldName'],
111
                    ])->first();
112
113
                    $collection_field->name = $column['name'];
114
                    $collection_field->old_name = $column['oldName'];
115
                    $collection_field->type = $column['type']['name'];
116
                    $collection_field->update();
117
                    $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
118
                } else {
119
                    $collection_field = new CollectionField;
120
121
                    $collection_field->dbm_collection_id = $id;
122
                    $collection_field->name = $column['name'];
123
                    $collection_field->old_name = $column['name'];
124
                    $collection_field->type = $column['type']['name'];
125
                    $collection_field->index = '';
126
                    $collection_field->extra = [];
127
128
                    $collection_field->save();
129
                }
130
            }
131
132
            if (count($fieldNames) > 0) {
133
                foreach ($fieldNames as $fieldName) {
134
                    $field = CollectionField::where([
135
                        'dbm_collection_id' => $id,
136
                        'name' => $fieldName, ])->first();
137
                    $field->delete();
138
                }
139
            }
140
        }
141
    }
142
143
    /**
144
     * Create|Update CRUD Field.
145
     *
146
     * @param \CodexShaper\DBM\Models\DBM_Object|\CodexShaper\DBM\Models\DBM_MongoObject $object
147
     * @param array $column
148
     * @param array $fieldNames
149
     *
150
     * @return \Illuminate\Http\JsonResponse|void
151
     */
152
    public function addOrUpdateCrudField($object, $column, &$fieldNames)
153
    {
154
        $columnType = $column['type'];
155
156
        if (in_array($column['oldName'], $fieldNames)) {
157
            $field = DBM::Field()->where([
158
                'dbm_object_id' => $object->id,
159
                'name' => $column['oldName'],
160
            ])->first();
161
162
            $field->name = $column['name'];
163
            if ($column['oldName'] != $column['name']) {
164
                $field->display_name = ucfirst($column['name']);
165
            }
166
            $field->order = $column['order'];
167
            $field->update();
168
169
            $fieldNames = array_values(array_diff($fieldNames, [$column['oldName']]));
170
        } else {
171
            if (DBM::Field()->where([
172
                'dbm_object_id' => $object->id,
173
                'name' => $column['name'], ])->first()) {
174
                return response()->json([
175
                    'success' => false,
176
                    'errors' => ['Field name must be unique. '.$column['name'].' are duplicate'],
177
                ], 400);
178
            }
179
180
            $field = DBM::Field();
181
            $field->dbm_object_id = $object->id;
182
            $field->name = $column['name'];
183
            $field->display_name = ucfirst($column['name']);
184
            $field->type = static::getInputType($columnType['name']);
185
            $field->order = $column['order'];
186
187
            if ($column['autoincrement'] == true) {
188
                $field->create = false;
189
                $field->read = false;
190
                $field->edit = false;
191
                $field->delete = false;
192
            }
193
194
            $field->save();
195
        }
196
    }
197
198
    /**
199
     * Update CRUD Fields.
200
     *
201
     * @param array $table
202
     *
203
     * @return void
204
     */
205
    public function updateCrudFields($table)
206
    {
207
        $tableName = $table['oldName'];
208
        $newName = $table['name'];
209
        $columns = $table['columns'];
210
211
        if ($tableName != $newName) {
212
            DBM::Object()->where('slug', Str::slug($tableName))->update([
213
                'name' => $newName,
214
                'slug' => Str::slug($newName),
215
                'display_name' => ucfirst($newName),
216
            ]);
217
218
            $tableName = $newName;
219
        }
220
221
        if ($object = DBM::Object()::where('slug', Str::slug($tableName))->first()) {
222
            $fieldNames = $object->fields->pluck('name')->toArray();
0 ignored issues
show
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

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