ModulsController   F
last analyzed

Complexity

Total Complexity 85

Size/Duplication

Total Lines 775
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 85
eloc 486
dl 0
loc 775
rs 2
c 1
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A getCheckSlug() 0 6 1
B getStep1() 0 33 8
A getStep3() 0 28 5
A getAdd() 0 12 3
A hook_before_delete() 0 5 1
B getStep2() 0 38 6
A postEditSave() 0 27 4
A getTableColumns() 0 5 1
A getStep4() 0 25 4
B postStep2() 0 81 9
B postAddSave() 0 93 7
A getTypeInfo() 0 4 1
B postStep3() 0 74 11
A postStepFinish() 0 46 5
C cbInit() 0 169 9
B postStep4() 0 88 9
A hook_query_index() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like ModulsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ModulsController, and based on these observations, apply Extract Interface, too.

1
<?php namespace crocodicstudio\crudbooster\controllers;
2
3
use CRUDBooster;
0 ignored issues
show
Bug introduced by
The type CRUDBooster 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...
4
use Illuminate\Support\Facades\DB;
5
use Illuminate\Support\Facades\Excel;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Excel 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...
6
use Illuminate\Support\Facades\PDF;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\PDF 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...
7
use Illuminate\Support\Facades\Request;
8
use Illuminate\Support\Facades\Session;
9
use crocodicstudio\crudbooster\fonts\Fontawesome;
10
11
class ModulsController extends CBController
12
{
13
    public function cbInit()
14
    {
15
        $this->table = 'cms_moduls';
16
        $this->primary_key = 'id';
17
        $this->title_field = "name";
18
        $this->limit = 100;
19
        $this->button_add = false;
20
        $this->button_export = false;
21
        $this->button_import = false;
22
        $this->button_filter = false;
23
        $this->button_detail = false;
24
        $this->button_bulk_action = false;
25
        $this->button_action_style = 'button_icon';
26
        $this->orderby = ['is_protected' => 'asc', 'name' => 'asc'];
27
28
        $this->col = [];
29
        $this->col[] = ["label" => "Name", "name" => "name"];
30
        $this->col[] = ["label" => "Table", "name" => "table_name"];
31
        $this->col[] = ["label" => "Path", "name" => "path"];
32
        $this->col[] = ["label" => "Controller", "name" => "controller"];
33
        $this->col[] = ["label" => "Protected", "name" => "is_protected", "visible" => false];
34
35
        $this->form = [];
36
        $this->form[] = ["label" => "Name", "name" => "name", "placeholder" => "Module name here", 'required' => true];
37
38
        $tables = CRUDBooster::listTables();
39
        $tables_list = [];
40
        foreach ($tables as $tab) {
41
            foreach ($tab as $key => $value) {
42
                $label = $value;
43
44
                if (substr($value, 0, 4) == 'cms_') {
45
                    continue;
46
                }
47
48
                $tables_list[] = $value."|".$label;
49
            }
50
        }
51
        foreach ($tables as $tab) {
52
            foreach ($tab as $key => $value) {
53
                $label = "[Default] ".$value;
54
                if (substr($value, 0, 4) == 'cms_') {
55
                    $tables_list[] = $value."|".$label;
56
                }
57
            }
58
        }
59
60
        $this->form[] = ["label" => "Table Name", "name" => "table_name", "type" => "select2", "dataenum" => $tables_list, 'required' => true];
61
62
        $fontawesome = Fontawesome::getIcons();
63
64
        $row = CRUDBooster::first($this->table, CRUDBooster::getCurrentId());
65
        $custom = view('crudbooster::components.list_icon', compact('fontawesome', 'row'))->render();
66
        $this->form[] = ['label' => 'Icon', 'name' => 'icon', 'type' => 'custom', 'html' => $custom, 'required' => true];
67
68
        $this->script_js = "
69
 			$(function() {
70
 				$('#table_name').change(function() {
71
					var v = $(this).val();
72
					$('#path').val(v);
73
				})	
74
 			})
75
 			";
76
77
        $this->form[] = ["label" => "Path", "name" => "path", "required" => true, 'placeholder' => 'Optional'];
78
        $this->form[] = ["label" => "Controller", "name" => "controller", "type" => "text", "placeholder" => "(Optional) Auto Generated"];
79
80
        if (CRUDBooster::getCurrentMethod() == 'getAdd' || CRUDBooster::getCurrentMethod() == 'postAddSave') {
81
82
            $this->form[] = [
83
                "label" => "Global Privilege",
84
                "name" => "global_privilege",
85
                "type" => "radio",
86
                "dataenum" => ['0|No', '1|Yes'],
87
                'value' => 0,
88
                'help' => 'Global Privilege allows you to make the module to be accessible by all privileges',
89
                'exception' => true,
90
            ];
91
92
            $this->form[] = [
93
                "label" => "Button Action Style",
94
                "name" => "button_action_style",
95
                "type" => "radio",
96
                "dataenum" => ['button_icon', 'button_icon_text', 'button_text', 'dropdown'],
97
                'value' => 'button_icon',
98
                'exception' => true,
99
            ];
100
            $this->form[] = [
101
                "label" => "Button Table Action",
102
                "name" => "button_table_action",
103
                "type" => "radio",
104
                "dataenum" => ['Yes', 'No'],
105
                'value' => 'Yes',
106
                'exception' => true,
107
            ];
108
            $this->form[] = [
109
                "label" => "Button Add",
110
                "name" => "button_add",
111
                "type" => "radio",
112
                "dataenum" => ['Yes', 'No'],
113
                'value' => 'Yes',
114
                'exception' => true,
115
            ];
116
            $this->form[] = [
117
                "label" => "Button Delete",
118
                "name" => "button_delete",
119
                "type" => "radio",
120
                "dataenum" => ['Yes', 'No'],
121
                'value' => 'Yes',
122
                'exception' => true,
123
            ];
124
            $this->form[] = [
125
                "label" => "Button Edit",
126
                "name" => "button_edit",
127
                "type" => "radio",
128
                "dataenum" => ['Yes', 'No'],
129
                'value' => 'Yes',
130
                'exception' => true,
131
            ];
132
            $this->form[] = [
133
                "label" => "Button Detail",
134
                "name" => "button_detail",
135
                "type" => "radio",
136
                "dataenum" => ['Yes', 'No'],
137
                'value' => 'Yes',
138
                'exception' => true,
139
            ];
140
            $this->form[] = [
141
                "label" => "Button Show",
142
                "name" => "button_show",
143
                "type" => "radio",
144
                "dataenum" => ['Yes', 'No'],
145
                'value' => 'Yes',
146
                'exception' => true,
147
            ];
148
            $this->form[] = [
149
                "label" => "Button Filter",
150
                "name" => "button_filter",
151
                "type" => "radio",
152
                "dataenum" => ['Yes', 'No'],
153
                'value' => 'Yes',
154
                'exception' => true,
155
            ];
156
            $this->form[] = [
157
                "label" => "Button Export",
158
                "name" => "button_export",
159
                "type" => "radio",
160
                "dataenum" => ['Yes', 'No'],
161
                'value' => 'No',
162
                'exception' => true,
163
            ];
164
            $this->form[] = [
165
                "label" => "Button Import",
166
                "name" => "button_import",
167
                "type" => "radio",
168
                "dataenum" => ['Yes', 'No'],
169
                'value' => 'No',
170
                'exception' => true,
171
            ];
172
        }
173
174
        $this->addaction[] = [
175
            'label' => 'Module Wizard',
176
            'icon' => 'fa fa-wrench',
177
            'url' => CRUDBooster::mainpath('step1').'/[id]',
178
            "showIf" => "[is_protected] == 0",
179
        ];
180
181
        $this->index_button[] = ['label' => 'Generate New Module', 'icon' => 'fa fa-plus', 'url' => CRUDBooster::mainpath('step1'), 'color' => 'success'];
182
    }
183
184
    function hook_query_index(&$query)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
185
    {
186
        $query->where('is_protected', 0);
187
        $query->whereNotIn('cms_moduls.controller', ['AdminCmsUsersController']);
188
    }
189
190
    function hook_before_delete($id)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
191
    {
192
        $modul = DB::table('cms_moduls')->where('id', $id)->first();
193
        $menus = DB::table('cms_menus')->where('path', 'like', '%'.$modul->controller.'%')->delete();
0 ignored issues
show
Unused Code introduced by
The assignment to $menus is dead and can be removed.
Loading history...
194
        @unlink(app_path('Http/Controllers/'.$modul->controller.'.php'));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

194
        /** @scrutinizer ignore-unhandled */ @unlink(app_path('Http/Controllers/'.$modul->controller.'.php'));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
195
    }
196
197
    public function getTableColumns($table)
198
    {
199
        $columns = CRUDBooster::getTableColumns($table);
200
201
        return response()->json($columns);
202
    }
203
204
    public function getCheckSlug($slug)
205
    {
206
        $check = DB::table('cms_moduls')->where('path', $slug)->count();
207
        $lastId = DB::table('cms_moduls')->max('id') + 1;
208
209
        return response()->json(['total' => $check, 'lastid' => $lastId]);
210
    }
211
212
    public function getAdd()
213
    {
214
        $this->cbLoader();
215
216
        $module = CRUDBooster::getCurrentModule();
217
218
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
219
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
220
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
221
        }
222
223
        return redirect()->route("ModulsControllerGetStep1");
224
    }
225
226
    public function getStep1($id = 0)
227
    {
228
        $this->cbLoader();
229
230
        $module = CRUDBooster::getCurrentModule();
231
232
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
233
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
234
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
235
        }
236
237
        $tables = CRUDBooster::listTables();
238
        $tables_list = [];
239
        foreach ($tables as $tab) {
240
            foreach ($tab as $key => $value) {
241
                $label = $value;
242
243
                if (substr($label, 0, 4) == 'cms_' && $label != config('crudbooster.USER_TABLE')) {
244
                    continue;
245
                }
246
                if ($label == 'migrations') {
247
                    continue;
248
                }
249
250
                $tables_list[] = $value;
251
            }
252
        }
253
254
        $fontawesome = Fontawesome::getIcons();
255
256
        $row = CRUDBooster::first($this->table, ['id' => $id]);
257
258
        return view("crudbooster::module_generator.step1", compact("tables_list", "fontawesome", "row", "id"));
259
    }
260
261
    public function getStep2($id)
262
    {
263
        $this->cbLoader();
264
265
        $module = CRUDBooster::getCurrentModule();
266
267
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
268
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
269
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
270
        }
271
272
        $row = DB::table('cms_moduls')->where('id', $id)->first();
273
274
        $columns = CRUDBooster::getTableColumns($row->table_name);
275
276
        $tables = CRUDBooster::listTables();
277
        $table_list = [];
278
        foreach ($tables as $tab) {
279
            foreach ($tab as $key => $value) {
280
                $label = $value;
0 ignored issues
show
Unused Code introduced by
The assignment to $label is dead and can be removed.
Loading history...
281
                $table_list[] = $value;
282
            }
283
        }
284
285
        if (file_exists(app_path('Http/Controllers/'.str_replace('.', '', $row->controller).'.php'))) {
286
            $response = file_get_contents(app_path('Http/Controllers/'.$row->controller.'.php'));
287
            $column_datas = extract_unit($response, "# START COLUMNS DO NOT REMOVE THIS LINE", "# END COLUMNS DO NOT REMOVE THIS LINE");
288
            $column_datas = str_replace('$this->', '$cb_', $column_datas);
289
            eval($column_datas);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
290
        }
291
292
        $data = [];
293
        $data['id'] = $id;
294
        $data['columns'] = $columns;
295
        $data['table_list'] = $table_list;
296
        $data['cb_col'] = $cb_col;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $cb_col seems to be never defined.
Loading history...
297
298
        return view('crudbooster::module_generator.step2', $data);
299
    }
300
301
    public function postStep2()
302
    {
303
        $this->cbLoader();
304
305
        $module = CRUDBooster::getCurrentModule();
306
307
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
308
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
309
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
310
        }
311
312
        $name = Request::get('name');
313
        $table_name = Request::get('table');
314
        $icon = Request::get('icon');
315
        $path = Request::get('path');
316
317
        if (! Request::get('id')) {
318
319
            if (DB::table('cms_moduls')->where('path', $path)->where('deleted_at', null)->count()) {
320
                return redirect()->back()->with(['message' => 'Sorry the slug has already exists, please choose another !', 'message_type' => 'warning']);
321
            }
322
323
            $created_at = now();
324
            $id = DB::table($this->table)->max('id') + 1;
325
326
            $controller = CRUDBooster::generateController($table_name, $path);
327
            DB::table($this->table)->insert(compact("controller", "name", "table_name", "icon", "path", "created_at", "id"));
328
329
            //Insert Menu
330
            if ($controller && Request::get('create_menu')) {
331
                $parent_menu_sort = DB::table('cms_menus')->where('parent_id', 0)->max('sorting') + 1;
332
333
                $id_cms_menus = DB::table('cms_menus')->insertGetId([
334
335
                    'created_at' => date('Y-m-d H:i:s'),
336
                    'name' => $name,
337
                    'icon' => $icon,
338
                    'path' => $controller.'GetIndex',
339
                    'type' => 'Route',
340
                    'is_active' => 1,
341
                    'id_cms_privileges' => CRUDBooster::myPrivilegeId(),
342
                    'sorting' => $parent_menu_sort,
343
                    'parent_id' => 0,
344
                ]);
345
                DB::table('cms_menus_privileges')->insert(['id_cms_menus' => $id_cms_menus, 'id_cms_privileges' => CRUDBooster::myPrivilegeId()]);
346
            }
347
348
            $user_id_privileges = CRUDBooster::myPrivilegeId();
349
            DB::table('cms_privileges_roles')->insert([
350
                'id' => DB::table('cms_privileges_roles')->max('id') + 1,
351
                'id_cms_moduls' => $id,
352
                'id_cms_privileges' => $user_id_privileges,
353
                'is_visible' => 1,
354
                'is_create' => 1,
355
                'is_read' => 1,
356
                'is_edit' => 1,
357
                'is_delete' => 1,
358
            ]);
359
360
            //Refresh Session Roles
361
            $roles = DB::table('cms_privileges_roles')->where('id_cms_privileges', CRUDBooster::myPrivilegeId())->join('cms_moduls', 'cms_moduls.id', '=', 'id_cms_moduls')->select('cms_moduls.name', 'cms_moduls.path', 'is_visible', 'is_create', 'is_read', 'is_edit', 'is_delete')->get();
362
            Session::put('admin_privileges_roles', $roles);
363
364
            return redirect(Route("ModulsControllerGetStep2", ["id" => $id]));
365
        } else {
366
            $id = Request::get('id');
367
            DB::table($this->table)->where('id', $id)->update(compact("name", "table_name", "icon", "path"));
368
369
            $row = DB::table('cms_moduls')->where('id', $id)->first();
370
371
            if (file_exists(app_path('Http/Controllers/'.$row->controller.'.php'))) {
372
                $response = file_get_contents(app_path('Http/Controllers/'.str_replace('.', '', $row->controller).'.php'));
373
            } else {
374
                $response = file_get_contents(__DIR__.'/'.str_replace('.', '', $row->controller).'.php');
375
            }
376
377
            if (strpos($response, "# START COLUMNS") !== true) {
378
                // return redirect()->back()->with(['message'=>'Sorry, is not possible to edit the module with Module Generator Tool. Prefix and or Suffix tag is missing !','message_type'=>'warning']);
379
            }
380
381
            return redirect(Route("ModulsControllerGetStep2", ["id" => $id]));
382
        }
383
    }
384
385
    public function postStep3()
386
    {
387
        $this->cbLoader();
388
389
        $module = CRUDBooster::getCurrentModule();
390
391
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
392
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
393
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
394
        }
395
396
        $column = Request::input('column');
397
        $name = Request::input('name');
398
        $join_table = Request::input('join_table');
399
        $join_field = Request::input('join_field');
400
        $is_image = Request::input('is_image');
401
        $is_download = Request::input('is_download');
0 ignored issues
show
Unused Code introduced by
The assignment to $is_download is dead and can be removed.
Loading history...
402
        $callbackphp = Request::input('callbackphp');
403
        $id = Request::input('id');
404
        $width = Request::input('width');
405
406
        $row = DB::table('cms_moduls')->where('id', $id)->first();
407
408
        $i = 0;
409
        $script_cols = [];
410
        foreach ($column as $col) {
411
412
            if (! $name[$i]) {
413
                $i++;
414
                continue;
415
            }
416
417
            $script_cols[$i] = "\t\t\t".'$this->col[] = ["label"=>"'.$col.'","name"=>"'.$name[$i].'"';
418
419
            if ($join_table[$i] && $join_field[$i]) {
420
                $script_cols[$i] .= ',"join"=>"'.$join_table[$i].','.$join_field[$i].'"';
421
            }
422
423
            if ($is_image[$i]) {
424
                $script_cols[$i] .= ',"image"=>true';
425
            }
426
427
            if ($id_download[$i]) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id_download does not exist. Did you maybe mean $is_download?
Loading history...
428
                $script_cols[$i] .= ',"download"=>true';
429
            }
430
431
            if ($width[$i]) {
432
                $script_cols[$i] .= ',"width"=>"'.$width[$i].'"';
433
            }
434
435
            if ($callbackphp[$i]) {
436
                $script_cols[$i] .= ',"callback_php"=>\''.$callbackphp[$i].'\'';
437
            }
438
439
            $script_cols[$i] .= "];";
440
441
            $i++;
442
        }
443
444
        $scripts = implode("\n", $script_cols);
445
        $raw = file_get_contents(app_path('Http/Controllers/'.$row->controller.'.php'));
446
        $raw = explode("# START COLUMNS DO NOT REMOVE THIS LINE", $raw);
447
        $rraw = explode("# END COLUMNS DO NOT REMOVE THIS LINE", $raw[1]);
448
449
        $file_controller = trim($raw[0])."\n\n";
450
        $file_controller .= "\t\t\t# START COLUMNS DO NOT REMOVE THIS LINE\n";
451
        $file_controller .= "\t\t\t".'$this->col = [];'."\n";
452
        $file_controller .= $scripts."\n";
453
        $file_controller .= "\t\t\t# END COLUMNS DO NOT REMOVE THIS LINE\n\n";
454
        $file_controller .= "\t\t\t".trim($rraw[1]);
455
456
        file_put_contents(app_path('Http/Controllers/'.$row->controller.'.php'), $file_controller);
457
458
        return redirect(Route("ModulsControllerGetStep3", ["id" => $id]));
459
    }
460
461
    public function getStep3($id)
462
    {
463
        $this->cbLoader();
464
465
        $module = CRUDBooster::getCurrentModule();
466
467
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
468
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
469
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
470
        }
471
472
        $row = DB::table('cms_moduls')->where('id', $id)->first();
473
474
        $columns = CRUDBooster::getTableColumns($row->table_name);
475
476
        if (file_exists(app_path('Http/Controllers/'.$row->controller.'.php'))) {
477
            $response = file_get_contents(app_path('Http/Controllers/'.$row->controller.'.php'));
478
            $column_datas = extract_unit($response, "# START FORM DO NOT REMOVE THIS LINE", "# END FORM DO NOT REMOVE THIS LINE");
479
            $column_datas = str_replace('$this->', '$cb_', $column_datas);
480
            eval($column_datas);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
481
        }
482
483
        $types = [];
484
        foreach (glob(base_path('vendor/crocodicstudio/crudbooster/src/views/default/type_components').'/*', GLOB_ONLYDIR) as $dir) {
485
            $types[] = basename($dir);
486
        }
487
488
        return view('crudbooster::module_generator.step3', compact('columns', 'cb_form', 'types', 'id'));
489
    }
490
491
    public function getTypeInfo($type = 'text')
492
    {
493
        header("Content-Type: application/json");
494
        echo file_get_contents(base_path('vendor/crocodicstudio/crudbooster/src/views/default/type_components/'.$type.'/info.json'));
495
    }
496
497
    public function postStep4()
498
    {
499
        $this->cbLoader();
500
501
        $post = Request::all();
502
        $id = $post['id'];
503
504
        $label = $post['label'];
505
        $name = $post['name'];
506
        $width = $post['width'];
507
        $type = $post['type'];
508
        $option = $post['option'];
509
        $validation = $post['validation'];
510
511
        $row = DB::table('cms_moduls')->where('id', $id)->first();
512
513
        $i = 0;
514
        $script_form = [];
515
        foreach ($label as $l) {
516
517
            if ($l != '') {
518
519
                $form = [];
520
                $form['label'] = $l;
521
                $form['name'] = $name[$i];
522
                $form['type'] = $type[$i];
523
                $form['validation'] = $validation[$i];
524
                $form['width'] = $width[$i];
525
                if ($option[$i]) {
526
                    $form = array_merge($form, $option[$i]);
527
                }
528
529
                foreach ($form as $k => $f) {
530
                    if ($f == '') {
531
                        unset($form[$k]);
532
                    }
533
                }
534
535
                $script_form[$i] = "\t\t\t".'$this->form[] = '.min_var_export($form).";";
536
            }
537
538
            $i++;
539
        }
540
541
        $scripts = implode("\n", $script_form);
542
        $raw = file_get_contents(app_path('Http/Controllers/'.$row->controller.'.php'));
543
        $raw = explode("# START FORM DO NOT REMOVE THIS LINE", $raw);
544
        $rraw = explode("# END FORM DO NOT REMOVE THIS LINE", $raw[1]);
545
546
        $top_script = trim($raw[0]);
547
        $current_scaffolding_form = trim($rraw[0]);
548
        $bottom_script = trim($rraw[1]);
549
550
        //IF FOUND OLD, THEN CLEAR IT
551
        if (strpos($bottom_script, '# OLD START FORM') !== false) {
552
            $line_end_count = strlen('# OLD END FORM');
553
            $line_start_old = strpos($bottom_script, '# OLD START FORM');
554
            $line_end_old = strpos($bottom_script, '# OLD END FORM') + $line_end_count;
555
            $get_string = substr($bottom_script, $line_start_old, $line_end_old);
556
            $bottom_script = str_replace($get_string, '', $bottom_script);
557
        }
558
559
        //ARRANGE THE FULL SCRIPT
560
        $file_controller = $top_script."\n\n";
561
        $file_controller .= "\t\t\t# START FORM DO NOT REMOVE THIS LINE\n";
562
        $file_controller .= "\t\t\t".'$this->form = [];'."\n";
563
        $file_controller .= $scripts."\n";
564
        $file_controller .= "\t\t\t# END FORM DO NOT REMOVE THIS LINE\n\n";
565
566
        //CREATE A BACKUP SCAFFOLDING TO OLD TAG
567
        if ($current_scaffolding_form) {
568
            $current_scaffolding_form = preg_split("/\\r\\n|\\r|\\n/", $current_scaffolding_form);
569
            foreach ($current_scaffolding_form as &$c) {
570
                $c = "\t\t\t//".trim($c);
571
            }
572
            $current_scaffolding_form = implode("\n", $current_scaffolding_form);
0 ignored issues
show
Bug introduced by
It seems like $current_scaffolding_form can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

572
            $current_scaffolding_form = implode("\n", /** @scrutinizer ignore-type */ $current_scaffolding_form);
Loading history...
573
574
            $file_controller .= "\t\t\t# OLD START FORM\n";
575
            $file_controller .= $current_scaffolding_form."\n";
576
            $file_controller .= "\t\t\t# OLD END FORM\n\n";
577
        }
578
579
        $file_controller .= "\t\t\t".trim($bottom_script);
580
581
        //CREATE FILE CONTROLLER
582
        file_put_contents(app_path('Http/Controllers/'.$row->controller.'.php'), $file_controller);
583
584
        return redirect(Route("ModulsControllerGetStep4", ["id" => $id]));
585
    }
586
587
    public function getStep4($id)
588
    {
589
        $this->cbLoader();
590
591
        $module = CRUDBooster::getCurrentModule();
592
593
        if (! CRUDBooster::isView() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
594
            CRUDBooster::insertLog(trans('crudbooster.log_try_view', ['module' => $module->name]));
595
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
596
        }
597
598
        $row = DB::table('cms_moduls')->where('id', $id)->first();
599
600
        $data = [];
601
        $data['id'] = $id;
602
        if (file_exists(app_path('Http/Controllers/'.$row->controller.'.php'))) {
603
            $response = file_get_contents(app_path('Http/Controllers/'.$row->controller.'.php'));
604
            $column_datas = extract_unit($response, "# START CONFIGURATION DO NOT REMOVE THIS LINE", "# END CONFIGURATION DO NOT REMOVE THIS LINE");
605
            $column_datas = str_replace('$this->', '$data[\'cb_', $column_datas);
606
            $column_datas = str_replace(' = ', '\'] = ', $column_datas);
607
            $column_datas = str_replace([' ', "\t"], '', $column_datas);
608
            eval($column_datas);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
609
        }
610
611
        return view('crudbooster::module_generator.step4', $data);
612
    }
613
614
    public function postStepFinish()
615
    {
616
        $this->cbLoader();
617
        $id = Request::input('id');
618
        $row = DB::table('cms_moduls')->where('id', $id)->first();
619
620
        $post = Request::all();
621
622
        $post['table'] = $row->table_name;
623
624
        $script_config = [];
625
        $exception = ['_token', 'id', 'submit'];
626
        $i = 0;
627
        foreach ($post as $key => $val) {
628
            if (in_array($key, $exception)) {
629
                continue;
630
            }
631
632
            if ($val != 'true' && $val != 'false') {
633
                $value = '"'.$val.'"';
634
            } else {
635
                $value = $val;
636
            }
637
638
            // if($key == 'orderby') {
639
            // 	$value = ;
640
            // }
641
642
            $script_config[$i] = "\t\t\t".'$this->'.$key.' = '.$value.';';
643
            $i++;
644
        }
645
646
        $scripts = implode("\n", $script_config);
647
        $raw = file_get_contents(app_path('Http/Controllers/'.$row->controller.'.php'));
648
        $raw = explode("# START CONFIGURATION DO NOT REMOVE THIS LINE", $raw);
649
        $rraw = explode("# END CONFIGURATION DO NOT REMOVE THIS LINE", $raw[1]);
650
651
        $file_controller = trim($raw[0])."\n\n";
652
        $file_controller .= "\t\t\t# START CONFIGURATION DO NOT REMOVE THIS LINE\n";
653
        $file_controller .= $scripts."\n";
654
        $file_controller .= "\t\t\t# END CONFIGURATION DO NOT REMOVE THIS LINE\n\n";
655
        $file_controller .= "\t\t\t".trim($rraw[1]);
656
657
        file_put_contents(app_path('Http/Controllers/'.$row->controller.'.php'), $file_controller);
658
659
        return redirect()->route('ModulsControllerGetIndex')->with(['message' => trans('crudbooster.alert_update_data_success'), 'message_type' => 'success']);
660
    }
661
662
    public function postAddSave()
663
    {
664
        $this->cbLoader();
665
666
        if (! CRUDBooster::isCreate() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
667
            CRUDBooster::insertLog(trans('crudbooster.log_try_add_save', [
668
                'name' => Request::input($this->title_field),
669
                'module' => CRUDBooster::getCurrentModule()->name,
670
            ]));
671
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans("crudbooster.denied_access"));
672
        }
673
674
        $this->validation();
675
        $this->input_assignment();
676
677
        //Generate Controller
678
        $route_basename = basename(Request::get('path'));
679
        if ($this->arr['controller'] == '') {
680
            $this->arr['controller'] = CRUDBooster::generateController(Request::get('table_name'), $route_basename);
681
        }
682
683
        $this->arr['created_at'] = date('Y-m-d H:i:s');
684
        $this->arr['id'] = DB::table($this->table)->max('id') + 1;
685
        DB::table($this->table)->insert($this->arr);
686
687
        //Insert Menu
688
        if ($this->arr['controller']) {
689
            $parent_menu_sort = DB::table('cms_menus')->where('parent_id', 0)->max('sorting') + 1;
690
            $parent_menu_id = DB::table('cms_menus')->max('id') + 1;
691
            DB::table('cms_menus')->insert([
692
                'id' => $parent_menu_id,
693
                'created_at' => date('Y-m-d H:i:s'),
694
                'name' => $this->arr['name'],
695
                'icon' => $this->arr['icon'],
696
                'path' => '#',
697
                'type' => 'URL External',
698
                'is_active' => 1,
699
                'id_cms_privileges' => CRUDBooster::myPrivilegeId(),
700
                'sorting' => $parent_menu_sort,
701
                'parent_id' => 0,
702
            ]);
703
            DB::table('cms_menus')->insert([
704
                'id' => DB::table('cms_menus')->max('id') + 1,
705
                'created_at' => date('Y-m-d H:i:s'),
706
                'name' => trans("crudbooster.text_default_add_new_module", ['module' => $this->arr['name']]),
707
                'icon' => 'fa fa-plus',
708
                'path' => $this->arr['controller'].'GetAdd',
709
                'type' => 'Route',
710
                'is_active' => 1,
711
                'id_cms_privileges' => CRUDBooster::myPrivilegeId(),
712
                'sorting' => 1,
713
                'parent_id' => $parent_menu_id,
714
            ]);
715
            DB::table('cms_menus')->insert([
716
                'id' => DB::table('cms_menus')->max('id') + 1,
717
                'created_at' => date('Y-m-d H:i:s'),
718
                'name' => trans("crudbooster.text_default_list_module", ['module' => $this->arr['name']]),
719
                'icon' => 'fa fa-bars',
720
                'path' => $this->arr['controller'].'GetIndex',
721
                'type' => 'Route',
722
                'is_active' => 1,
723
                'id_cms_privileges' => CRUDBooster::myPrivilegeId(),
724
                'sorting' => 2,
725
                'parent_id' => $parent_menu_id,
726
            ]);
727
        }
728
729
        $id_modul = $this->arr['id'];
730
731
        $user_id_privileges = CRUDBooster::myPrivilegeId();
732
        DB::table('cms_privileges_roles')->insert([
733
            'id' => DB::table('cms_privileges_roles')->max('id') + 1,
734
            'id_cms_moduls' => $id_modul,
735
            'id_cms_privileges' => $user_id_privileges,
736
            'is_visible' => 1,
737
            'is_create' => 1,
738
            'is_read' => 1,
739
            'is_edit' => 1,
740
            'is_delete' => 1,
741
        ]);
742
743
        //Refresh Session Roles
744
        $roles = DB::table('cms_privileges_roles')->where('id_cms_privileges', CRUDBooster::myPrivilegeId())->join('cms_moduls', 'cms_moduls.id', '=', 'id_cms_moduls')->select('cms_moduls.name', 'cms_moduls.path', 'is_visible', 'is_create', 'is_read', 'is_edit', 'is_delete')->get();
745
        Session::put('admin_privileges_roles', $roles);
746
747
        $ref_parameter = Request::input('ref_parameter');
0 ignored issues
show
Unused Code introduced by
The assignment to $ref_parameter is dead and can be removed.
Loading history...
748
        if (Request::get('return_url')) {
749
            CRUDBooster::redirect(Request::get('return_url'), trans("crudbooster.alert_add_data_success"), 'success');
750
        } else {
751
            if (Request::get('submit') == trans('crudbooster.button_save_more')) {
752
                CRUDBooster::redirect(CRUDBooster::mainpath('add'), trans("crudbooster.alert_add_data_success"), 'success');
753
            } else {
754
                CRUDBooster::redirect(CRUDBooster::mainpath(), trans("crudbooster.alert_add_data_success"), 'success');
755
            }
756
        }
757
    }
758
759
    public function postEditSave($id)
760
    {
761
        $this->cbLoader();
762
763
        $row = DB::table($this->table)->where($this->primary_key, $id)->first();
764
765
        if (! CRUDBooster::isUpdate() && $this->global_privilege == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
766
            CRUDBooster::insertLog(trans("crudbooster.log_try_add", ['name' => $row->{$this->title_field}, 'module' => CRUDBooster::getCurrentModule()->name]));
767
            CRUDBooster::redirect(CRUDBooster::adminPath(), trans('crudbooster.denied_access'));
768
        }
769
770
        $this->validation();
771
        $this->input_assignment();
772
773
        //Generate Controller
774
        $route_basename = basename(Request::get('path'));
775
        if ($this->arr['controller'] == '') {
776
            $this->arr['controller'] = CRUDBooster::generateController(Request::get('table_name'), $route_basename);
777
        }
778
779
        DB::table($this->table)->where($this->primary_key, $id)->update($this->arr);
780
781
        //Refresh Session Roles
782
        $roles = DB::table('cms_privileges_roles')->where('id_cms_privileges', CRUDBooster::myPrivilegeId())->join('cms_moduls', 'cms_moduls.id', '=', 'id_cms_moduls')->select('cms_moduls.name', 'cms_moduls.path', 'is_visible', 'is_create', 'is_read', 'is_edit', 'is_delete')->get();
783
        Session::put('admin_privileges_roles', $roles);
784
785
        CRUDBooster::redirect(Request::server('HTTP_REFERER'), trans('crudbooster.alert_update_data_success'), 'success');
786
    }
787
}
788