Passed
Push — master ( 84b36f...a99c1b )
by Iman
04:15
created

AdminModulesController::makeForm()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 116
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 95
nc 2
nop 0
dl 0
loc 116
c 0
b 0
f 0
cc 2
rs 8.2857

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace crocodicstudio\crudbooster\Modules\ModuleGenerator;
4
5
use crocodicstudio\crudbooster\controllers\CBController;
6
use crocodicstudio\crudbooster\controllers\FormValidator;
7
use Illuminate\Support\Facades\Session;
8
use Illuminate\Support\Facades\Request;
9
use Illuminate\Support\Facades\DB;
10
use crocodicstudio\crudbooster\helpers\CRUDBooster;
11
12
class AdminModulesController extends CBController
13
{
14
    public function cbInit()
15
    {
16
        $this->table = 'cms_moduls';
17
        $this->primaryKey = 'id';
18
        $this->title_field = 'name' ;
19
        $this->limit = 100;
20
        $this->button_add = false;
0 ignored issues
show
Bug Best Practice introduced by
The property button_add does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
21
        $this->buttonExport = false;
22
        $this->button_import = false;
23
        $this->button_filter = false;
0 ignored issues
show
Bug Best Practice introduced by
The property button_filter does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
24
        $this->buttonDetail = false;
25
        $this->button_bulk_action = false;
0 ignored issues
show
Bug Best Practice introduced by
The property button_bulk_action does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
26
        $this->button_action_style = 'button_icon';
27
        $this->orderby = ['is_protected' => 'asc', 'name' => 'asc'];
28
29
        $this->col = [];
30
        $this->col[] = ['label' => 'name', 'name' => 'name' ];
31
        $this->col[] = ['label' => "Table", 'name' => "table_name"];
32
        $this->col[] = ['label' => "Path", 'name' => "path"];
33
        $this->col[] = ['label' => "Controller", 'name' => "controller"];
34
        $this->col[] = ['label' => "Protected", 'name' => "is_protected", "visible" => false];
35
36
        $this->form = Form::makeForm($this->table);
37
38
        $this->script_js = "
39
 			$(function() {
40
 				$('#table_name').change(function() {
41
					var v = $(this).val();
42
					$('#path').val(v);
43
				})	
44
 			}) ";
45
46
        $this->addaction[] = [
47
            'label' => 'Module Wizard',
48
            'icon' => 'fa fa-wrench',
49
            'url' => CRUDBooster::mainpath('step1').'/[id]',
50
            "showIf" => "[is_protected] == 0",
51
        ];
52
53
        $this->index_button[] = ['label' => 'Generate New Module', 'icon' => 'fa fa-plus', 'url' => CRUDBooster::mainpath('step1'), 'color' => 'success'];
54
    }
55
    // public function getIndex() {
56
    // 	$data['page_title'] = 'Module Generator';
57
    // 	$data['result'] = DB::table('cms_moduls')->where('is_protected',0)->orderby('name','asc')->get();
58
    // 	$this->cbView('CbModulesGen::index',$data);
59
    // }	
60
61
    function hookBeforeDelete($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...
62
    {
63
        $controller = ModulesRepo::getControllerName($id);
64
        DB::table('cms_menus')->where('path', 'like', '%'.$controller.'%')->delete();
65
        @unlink(controller_path($controller));
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

65
        /** @scrutinizer ignore-unhandled */ @unlink(controller_path($controller));

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...
66
    }
67
68
    public function getTableColumns($table)
69
    {
70
        $columns = \Schema::getColumnListing($table);
71
72
        return response()->json($columns);
0 ignored issues
show
Bug introduced by
The method json() does not exist on Symfony\Component\HttpFoundation\Response. It seems like you code against a sub-type of Symfony\Component\HttpFoundation\Response such as Illuminate\Http\Response or Illuminate\Http\JsonResponse or Illuminate\Http\RedirectResponse. ( Ignorable by Annotation )

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

72
        return response()->/** @scrutinizer ignore-call */ json($columns);
Loading history...
73
    }
74
75
    public function getCheckSlug($slug)
76
    {
77
        $check = DB::table('cms_moduls')->where('path', $slug)->count();
78
        $lastId = DB::table('cms_moduls')->max('id') + 1;
79
80
        return response()->json(['total' => $check, 'lastid' => $lastId]);
81
    }
82
83
    public function getAdd()
84
    {
85
        $this->cbLoader();
86
87
        return redirect()->route("ModulesControllerGetStep1");
88
    }
89
90
    public function getStep1($id = 0, Step1Handler $handler)
91
    {
92
        $this->cbLoader();
93
        return $handler->showForm($id);
94
    }
95
96
    public function getStep2($id, Step2Handler $handler)
97
    {
98
        $this->cbLoader();
99
        return $handler->showForm($id);
100
    }
101
102
    public function postStep2(Step1Handler $handler)
103
    {
104
        $this->cbLoader();
105
106
        return $handler->handleFormSubmit();
107
    }
108
109
    public function postStep3(Step2Handler $handler)
110
    {
111
        $this->cbLoader();
112
        return $handler->handleFormSubmit();
113
    }
114
115
    public function getStep3($id, Step3Handler $step3)
116
    {
117
        $this->cbLoader();
118
        return $step3->showForm($id);
119
    }
120
121
    public function getTypeInfo($type = 'text')
122
    {
123
        header("Content-Type: application/json");
124
        echo file_get_contents(CbComponentsPath($type).'/info.json');
125
    }
126
127
    public function postStep4(Step3Handler $handler)
128
    {
129
        $this->cbLoader();
130
        return $handler->handleFormSubmit();
131
    }
132
133
    public function getStep4($id, Step4Handler $handler)
134
    {
135
        $this->cbLoader();
136
        return $handler->showForm($id);
137
    }
138
139
    public function postStepFinish(Step4Handler $handler)
140
    {
141
        $this->cbLoader();
142
        return $handler->handleFormSubmit();
143
    }
144
145
    public function postAddSave()
146
    {
147
        $this->cbLoader();
148
        app(FormValidator::class)->validate(null, $this->form, $this->table);
149
        $this->inputAssignment();
150
151
        //Generate Controller 
152
        $route_basename = basename(request('path'));
0 ignored issues
show
Bug introduced by
It seems like request('path') can also be of type array; however, parameter $path of basename() does only seem to accept string, 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

152
        $route_basename = basename(/** @scrutinizer ignore-type */ request('path'));
Loading history...
153
        if ($this->arr['controller'] == '') {
154
            $this->arr['controller'] = ControllerGenerator::generateController(request('table_name'), $route_basename);
155
        }
156
157
        $this->arr['created_at'] = date('Y-m-d H:i:s');
158
        $this->arr['id'] = $this->table()->max('id') + 1;
159
        $this->table()->insert($this->arr);
160
161
        //Insert Menu
162
        if ($this->arr['controller']) {
163
            $this->createMenuForModule();
164
        }
165
166
        $id_modul = $this->arr['id'];
167
168
        $user_id_privileges = CRUDBooster::myPrivilegeId();
169
        DB::table('cms_privileges_roles')->insert([
170
            'id_cms_moduls' => $id_modul,
171
            'id_cms_privileges' => $user_id_privileges,
172
            'is_visible' => 1,
173
            'is_create' => 1,
174
            'is_read' => 1,
175
            'is_edit' => 1,
176
            'is_delete' => 1,
177
        ]);
178
179
        //Refresh Session Roles
180
        $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();
181
        Session::put('admin_privileges_roles', $roles);
182
183
        $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...
184
        if (request('return_url')) {
185
            CRUDBooster::redirect(request('return_url'), cbTrans("alert_add_data_success"), 'success');
186
        } 
187
        if (request('submit') == cbTrans('button_save_more')) {
188
            CRUDBooster::redirect(CRUDBooster::mainpath('add'), cbTrans('alert_add_data_success'), 'success');
189
        }
190
        CRUDBooster::redirect(CRUDBooster::mainpath(), cbTrans('alert_add_data_success'), 'success');
191
    }
192
193
    public function postEditSave($id)
194
    {
195
        $this->cbLoader();
196
197
        $row = $this->table()->where($this->primaryKey, $id)->first();
0 ignored issues
show
Unused Code introduced by
The assignment to $row is dead and can be removed.
Loading history...
198
199
200
        app(FormValidator::class)->validate($id, $this->form, $this->table);
201
202
        $this->inputAssignment();
203
204
        //Generate Controller 
205
        $route_basename = basename(request('path'));
0 ignored issues
show
Bug introduced by
It seems like request('path') can also be of type array; however, parameter $path of basename() does only seem to accept string, 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

205
        $route_basename = basename(/** @scrutinizer ignore-type */ request('path'));
Loading history...
206
        if ($this->arr['controller'] == '') {
207
            $this->arr['controller'] = ControllerGenerator::generateController(request('table_name'), $route_basename);
208
        }
209
210
        $this->findRow($id)->update($this->arr);
211
212
        //Refresh Session Roles
213
        $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();
214
        Session::put('admin_privileges_roles', $roles);
215
216
        CRUDBooster::redirect(Request::server('HTTP_REFERER'), cbTrans('alert_update_data_success'), 'success');
217
    }
218
219
    private function createMenuForModule()
220
    {
221
        $parent_menu_sort = DB::table('cms_menus')->where('parent_id', 0)->max('sorting') + 1;
222
        $parent_menu_id = DB::table('cms_menus')->insertGetId([
223
            'created_at' => date('Y-m-d H:i:s'),
224
            'name' => $this->arr['name'],
225
            'icon' => $this->arr['icon'],
226
            'path' => '#',
227
            'type' => 'URL External',
228
            'is_active' => 1,
229
            'cms_privileges' => CRUDBooster::myPrivilegeId(),
230
            'sorting' => $parent_menu_sort,
231
            'parent_id' => 0,
232
        ]);
233
234
        $arr = [
235
            'created_at' => date('Y-m-d H:i:s'),
236
            'type' => 'Route',
237
            'is_active' => 1,
238
            'cms_privileges' => CRUDBooster::myPrivilegeId(),
239
            'parent_id' => $parent_menu_id,
240
        ];
241
242
        DB::table('cms_menus')->insert([
243
            'name' => cbTrans('text_default_add_new_module', ['module' => $this->arr['name']]),
244
            'icon' => 'fa fa-plus',
245
            'path' => $this->arr['controller'].'GetAdd',
246
            'sorting' => 1,
247
        ] + $arr);
248
249
        DB::table('cms_menus')->insert([
250
            'name' => cbTrans('text_default_list_module', ['module' => $this->arr['name']]),
251
            'icon' => 'fa fa-bars',
252
            'path' => $this->arr['controller'].'GetIndex',
253
            'cms_privileges' => CRUDBooster::myPrivilegeId(),
254
            'sorting' => 2,
255
        ] + $arr);
256
257
    }
258
}
259