Passed
Push — master ( 72fffe...b949dd )
by Ferry
04:19
created

DeveloperModulesController::postCreateMigration()   C

Complexity

Conditions 9
Paths 318

Size

Total Lines 60
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 34
nc 318
nop 0
dl 0
loc 60
rs 5.7472
c 0
b 0
f 0

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
 * Created by PhpStorm.
4
 * User: User
5
 * Date: 4/25/2019
6
 * Time: 9:28 PM
7
 */
8
9
namespace crocodicstudio\crudbooster\controllers;
10
11
use crocodicstudio\crudbooster\exceptions\CBValidationException;
12
use crocodicstudio\crudbooster\helpers\ComposerHelper;
13
use crocodicstudio\crudbooster\helpers\ModuleGenerator;
14
use Illuminate\Support\Facades\Artisan;
15
use Illuminate\Support\Facades\DB;
16
use Illuminate\Support\Facades\Schema;
17
use Illuminate\Support\Str;
18
use Illuminate\Support\Facades\Cache;
19
use Symfony\Component\Process\Process;
20
21
class DeveloperModulesController extends Controller
22
{
23
24
    private $view = "crudbooster::dev_layouts.modules.modules";
25
26
    public function __construct()
27
    {
28
        view()->share(['page_title'=>'Module Manager']);
29
    }
30
31
32
    public function getIndex() {
33
        $data = [];
34
        $data['result'] = DB::table("cb_modules")->get();
35
        return view($this->view.'.index',$data);
36
    }
37
38
    public function getAdd() {
39
        $data = [];
40
        $data['tables'] = cb()->listAllTable();
41
        $data['module'] = (request('modules_id'))?cb()->find("cb_modules", request("modules_id")):null;
42
        return view($this->view.'.add', $data);
43
    }
44
45
    public function getTables()
46
    {
47
        return response()->json(cb()->listAllTable());
48
    }
49
50
    public function getAllColumn($table) {
51
        $data = cb()->listAllColumns($table);
52
        $pk = cb()->findPrimaryKey($table);
53
        $result = [];
54
        foreach($data as $item) {
55
56
            if(Str::contains(strtolower($item),["title","name","label"])) {
57
                $display = true;
58
            }else{
59
                $display = false;
60
            }
61
62
            $result[] = [
63
                "column"=>$item,
64
                "primary_key"=>($pk==$item)?true:false,
65
                "display"=>$display
66
            ];
67
        }
68
        return response()->json($result);
69
    }
70
71
    public function getColumns($table)
72
    {
73
        if(request("modules_id")) {
74
            $module = cb()->find("cb_modules",request("modules_id"));
75
            if($module->last_column_build) {
76
                return response()->json(json_decode($module->last_column_build));
77
            }
78
        }
79
80
        $columns = cb()->listAllColumns($table);
81
        $pk = cb()->findPrimaryKey($table);
82
        $result = [];
83
        foreach($columns as $column) {
84
            if($column != $pk) {
85
86
                // Skip Column
87
                if($column == 'deleted_at') continue;
88
89
                // Check if any relation table candidate
90
                $optionTable = "";
91
                if(Str::substr(strtolower($column),-3,3) == "_id") {
92
                    $relationTable = Str::substr($column,0,-3);
93
                    if(Schema::hasTable($relationTable)) {
94
                        $optionTable = $relationTable;
95
                    }
96
                }elseif (Str::substr(strtolower($column),0,3) == "id_") {
97
                    $relationTable = Str::substr($column,3);
98
                    if(Schema::hasTable($relationTable)) {
99
                        $optionTable = $relationTable;
100
                    }
101
                }
102
103
                $label = trim(Str::title(str_replace(["id_","_id","_"]," ",$column)));
104
                $label = Str::singular($label);
105
                $type = "text";
106
107
                if(Str::contains(strtolower($label),["photo","image","picture","gambar"])) {
108
                    $type = "image";
109
                }elseif (Str::contains(strtolower($label),["email","mail"])) {
110
                    $type = "email";
111
                }elseif (Str::contains(strtolower($label),["description","content","detail"])) {
112
                    $type =  "wysiwyg";
113
                }elseif (Str::contains(strtolower($label),["price","money","grand_total","tax"])) {
114
                    $type = "money";
115
                }elseif (Str::contains(strtolower($label),["quantity","qty","total","phone","telp"])) {
116
                    $type = "number";
117
                }elseif (Str::contains(strtolower($label),["date"])) {
118
                    $type = "date";
119
                }
120
121
                if (Str::substr(strtolower($column),-3,3) == "_id") {
122
                    $type = "select_table";
123
                } elseif (Str::substr($column, -3, 3) == "_at") {
124
                    $type = "datetime";
125
                } elseif (Str::substr($column,0, 3) == "id_") {
126
                    $type = "select_table";
127
                }
128
129
                $columnAdd = "on";
130
                $columnEdit = "on";
131
                $columnMandatory = "on";
132
                if(in_array($column,['created_at','updated_at'])) {
133
                    $columnAdd = "";
134
                    $columnEdit = "";
135
                    $columnMandatory = "";
136
                }
137
138
                $result[] = [
139
                    'column_label'=>$label,
140
                    'column_field'=> $column,
141
                    'column_type'=>$type,
142
                    'column_file_encrypt'=>"on",
143
                    'column_image_width'=>'',
144
                    'column_image_height'=>'',
145
                    'column_option_table'=>$optionTable,
146
                    'column_date_format'=>'',
147
                    'column_text_display_limit'=>150,
148
                    'column_text_max'=>255,
149
                    'column_text_min'=>0,
150
                    'column_money_prefix'=>'',
151
                    'column_money_precision'=>'',
152
                    'column_money_thousand_separator'=>'',
153
                    'column_money_decimal_separator'=>'',
154
                    'column_option_value'=> "",
155
                    'column_option_display'=> "",
156
                    'column_option_sql_condition'=> "",
157
                    'column_options'=> [],
158
                    'column_sql_query'=> "",
159
                    'column_help'=> "",
160
                    'column_mandatory'=> $columnMandatory,
161
                    'column_browse'=> "on",
162
                    'column_detail'=> "on",
163
                    'column_edit'=> $columnEdit,
164
                    'column_add'=> $columnAdd,
165
                    "column_filterable"=>"",
166
                    "column_foreign"=>"",
167
                    'listTableColumns'=> []
168
                ];
169
            }
170
        }
171
        return response()->json($result);
172
    }
173
174
    public function postCreateMigration()
175
    {
176
        try {
177
            cb()->validation(['table_name','structures']);
178
179
            $tableName = request("table_name");
180
181
            if(!Schema::hasTable($tableName)) {
0 ignored issues
show
Bug introduced by
It seems like $tableName can also be of type array; however, parameter $table of Illuminate\Database\Schema\Builder::hasTable() 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

181
            if(!Schema::hasTable(/** @scrutinizer ignore-type */ $tableName)) {
Loading history...
182
                $filenameMigration = date("Y_m_d_His")."_".$tableName.".php";
0 ignored issues
show
Bug introduced by
Are you sure $tableName of type Illuminate\Http\Request|array|string can be used in concatenation? ( Ignorable by Annotation )

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

182
                $filenameMigration = date("Y_m_d_His")."_"./** @scrutinizer ignore-type */ $tableName.".php";
Loading history...
183
                $createTemplate = file_get_contents(base_path("vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/create.stub"));
184
                $className = Str::studly($tableName);
0 ignored issues
show
Bug introduced by
It seems like $tableName can also be of type array; however, parameter $value of Illuminate\Support\Str::studly() 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

184
                $className = Str::studly(/** @scrutinizer ignore-type */ $tableName);
Loading history...
185
                $createTemplate = str_replace("DummyClass", $className, $createTemplate);
186
                $createTemplate = str_replace("DummyTable", $tableName, $createTemplate);
187
                $createTemplate = str_replace("\$table->increments('id');","",$createTemplate);
188
189
                $structureItems = "";
190
191
                if(request("timestamp")) {
192
                    $structureItems .= "\$table->timestamps();\n\t\t\t";
193
                }
194
195
                if(request("soft_deletes")) {
196
                    $structureItems .= "\$table->softDeletes();\n\t\t\t";
197
                }
198
199
                foreach(request("structures") as $item) {
200
201
                    $nullable = "";
202
203
                    if(!in_array($item['type_data'],["bigIncrements","increments","mediumIncrements","smallIncrements"])) {
204
                        $nullable = "->nullable()";
205
                    }
206
207
                    if($item['length']) {
208
                        $structureItems .= "\$table->".$item['type_data']."('".$item['field_name']."', ".$item['length'].")$nullable;\n\t\t\t";
209
                    }else{
210
                        $structureItems .= "\$table->".$item['type_data']."('".$item['field_name']."')$nullable;\n\t\t\t";
211
                    }
212
                }
213
                $createTemplate = str_replace("\$table->timestamps();", $structureItems, $createTemplate);
214
215
                // Put File onto the migration folders
216
                file_put_contents(database_path("migrations/".$filenameMigration), $createTemplate);
217
218
                // Composing
219
                ComposerHelper::dumpAutoLoad();
220
221
                // Migrate
222
                Artisan::call("migrate");
223
            } else {
224
                throw new \Exception("The table $tableName has already exists!");
225
            }
226
227
        } catch (CBValidationException $e) {
228
            return response()->json(['status'=>false,'message'=>$e->getMessage()]);
229
        } catch (\Exception $e) {
230
            return response()->json(['status'=>false,'message'=>$e->getMessage()]);
231
        }
232
233
        return response()->json(['status'=>true,'message'=>'Migration successfully!']);
234
    }
235
236
    public function postCheckExistModule()
237
    {
238
        try {
239
            cb()->validation(['name', 'table']);
240
241
            if(DB::table("cb_modules")->where("table_name",request("table"))->where("name",request("name"))->count()) {
242
                return response()->json(['status'=>true]);
243
            }
244
245
        } catch (CBValidationException $e) {
246
            return response()->json(['status'=>false,'message'=>$e->getMessage()]);
247
        }
248
249
        return response()->json(['status'=>false]);
250
    }
251
252
    public function postAddSave() {
253
254
        try {
255
            cb()->validation(['name', 'table','icon','columns']);
256
257
            $module = (new ModuleGenerator(request('table'), request('name'), request('icon'), request("columns"), request("rebuild")))->make();
258
259
        } catch (CBValidationException $e) {
260
            return response()->json(['status'=>false,'message'=>$e->getMessage()]);
261
        }
262
263
        return response()->json(['status'=>true, 'message'=>'Please remember that you can still modify the structure by edit the controller file '.$module['controller'].' :)']);
264
    }
265
266
    public function getDelete($id) {
267
        $module = cb()->find("cb_modules",$id);
268
        @unlink(app_path("Http/Controllers/".$module->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

268
        /** @scrutinizer ignore-unhandled */ @unlink(app_path("Http/Controllers/".$module->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...
269
        DB::table("cb_modules")->where("id", $id)->delete();
270
        DB::table("cb_menus")->where("cb_modules_id", $id)->delete();
271
        return cb()->redirectBack("The module has been deleted!","success");
272
    }
273
274
    public function getDeleteSoft($id) {
275
        $module = cb()->find("cb_modules",$id);
0 ignored issues
show
Unused Code introduced by
The assignment to $module is dead and can be removed.
Loading history...
276
        DB::table("cb_modules")->where("id", $id)->delete();
277
        DB::table("cb_menus")->where("cb_modules_id", $id)->delete();
278
        return cb()->redirectBack("The module has been deleted!","success");
279
    }
280
281
}