Passed
Push — master ( 5403d4...38a665 )
by Ferry
04:29
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\ModuleGenerator;
13
use Illuminate\Support\Facades\Artisan;
14
use Illuminate\Support\Facades\DB;
15
use Illuminate\Support\Facades\Schema;
16
use Illuminate\Support\Str;
17
use Illuminate\Support\Facades\Cache;
18
use Symfony\Component\Process\Process;
19
20
class DeveloperModulesController extends Controller
21
{
22
23
    private $view = "crudbooster::dev_layouts.modules.modules";
24
25
    public function __construct()
26
    {
27
        view()->share(['page_title'=>'Module Manager']);
28
    }
29
30
31
    public function getIndex() {
32
        $data = [];
33
        $data['result'] = DB::table("cb_modules")->get();
34
        return view($this->view.'.index',$data);
35
    }
36
37
    public function getAdd() {
38
        $data = [];
39
        $data['tables'] = cb()->listAllTable();
40
        $data['module'] = (request('modules_id'))?cb()->find("cb_modules", request("modules_id")):null;
41
        return view($this->view.'.add', $data);
42
    }
43
44
    public function getTables()
45
    {
46
        return response()->json(cb()->listAllTable());
47
    }
48
49
    public function getAllColumn($table) {
50
        $data = cb()->listAllColumns($table);
51
        $pk = cb()->findPrimaryKey($table);
52
        $result = [];
53
        foreach($data as $item) {
54
55
            if(Str::contains(strtolower($item),["title","name","label"])) {
56
                $display = true;
57
            }else{
58
                $display = false;
59
            }
60
61
            $result[] = [
62
                "column"=>$item,
63
                "primary_key"=>($pk==$item)?true:false,
64
                "display"=>$display
65
            ];
66
        }
67
        return response()->json($result);
68
    }
69
70
    public function getColumns($table)
71
    {
72
        if(request("modules_id")) {
73
            $module = cb()->find("cb_modules",request("modules_id"));
74
            if($module->last_column_build) {
75
                return response()->json(json_decode($module->last_column_build));
76
            }
77
        }
78
79
        $columns = cb()->listAllColumns($table);
80
        $pk = cb()->findPrimaryKey($table);
81
        $result = [];
82
        foreach($columns as $column) {
83
            if($column != $pk) {
84
85
                // Check if any relation table candidate
86
                $optionTable = "";
87
                if(Str::substr(strtolower($column),-3,3) == "_id") {
88
                    $relationTable = Str::substr($column,0,-3);
89
                    if(Schema::hasTable($relationTable)) {
90
                        $optionTable = $relationTable;
91
                    }
92
                }elseif (Str::substr(strtolower($column),0,3) == "id_") {
93
                    $relationTable = Str::substr($column,3);
94
                    if(Schema::hasTable($relationTable)) {
95
                        $optionTable = $relationTable;
96
                    }
97
                }
98
99
                $label = trim(Str::title(str_replace(["id_","_id","_"]," ",$column)));
100
                $label = Str::singular($label);
101
                $type = "text";
102
103
                if(Str::contains(strtolower($label),["photo","image","picture","gambar"])) {
104
                    $type = "image";
105
                }elseif (Str::contains(strtolower($label),["email","mail"])) {
106
                    $type = "email";
107
                }elseif (Str::contains(strtolower($label),["description","content","detail"])) {
108
                    $type =  "wysiwyg";
109
                }elseif (Str::contains(strtolower($label),["price","money","grand_total","tax"])) {
110
                    $type = "money";
111
                }elseif (Str::contains(strtolower($label),["quantity","qty","total","phone","telp"])) {
112
                    $type = "number";
113
                }elseif (Str::contains(strtolower($label),["date"])) {
114
                    $type = "date";
115
                }
116
117
                if (Str::substr(strtolower($column),-3,3) == "_id") {
118
                    $type = "select_table";
119
                } elseif (Str::substr($column, -3, 3) == "_at") {
120
                    $type = "datetime";
121
                } elseif (Str::substr($column,0, 3) == "id_") {
122
                    $type = "select_table";
123
                }
124
125
                $result[] = [
126
                    'column_label'=>$label,
127
                    'column_field'=> $column,
128
                    'column_type'=>$type,
129
                    'column_option_table'=>$optionTable,
130
                    'column_option_value'=> "",
131
                    'column_option_display'=> "",
132
                    'column_option_sql_condition'=> "",
133
                    'column_options'=> [],
134
                    'column_sql_query'=> "",
135
                    'column_help'=> "",
136
                    'column_mandatory'=> "on",
137
                    'column_browse'=> "on",
138
                    'column_detail'=> "on",
139
                    'column_edit'=> "on",
140
                    'column_add'=> "on",
141
                    'listTableColumns'=> []
142
                ];
143
            }
144
        }
145
        return response()->json($result);
146
    }
147
148
    private function findComposer()
149
    {
150
        if (file_exists(getcwd().'/composer.phar')) {
151
            return '"'.PHP_BINARY.'" '.getcwd().'/composer.phar';
152
        }
153
154
        return 'composer';
155
    }
156
157
    private function composingAutoLoad()
158
    {
159
        $composer = $this->findComposer();
160
        $process = new Process($composer.' dump-autoload');
0 ignored issues
show
Bug introduced by
$composer . ' dump-autoload' of type string is incompatible with the type array expected by parameter $command of Symfony\Component\Process\Process::__construct(). ( Ignorable by Annotation )

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

160
        $process = new Process(/** @scrutinizer ignore-type */ $composer.' dump-autoload');
Loading history...
161
        $process->setWorkingDirectory(base_path())->run();
162
    }
163
164
    public function postCreateMigration()
165
    {
166
        try {
167
            cb()->validation(['table_name','structures']);
168
169
            $tableName = request("table_name");
170
171
            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

171
            if(!Schema::hasTable(/** @scrutinizer ignore-type */ $tableName)) {
Loading history...
172
                $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

172
                $filenameMigration = date("Y_m_d_His")."_"./** @scrutinizer ignore-type */ $tableName.".php";
Loading history...
173
                $createTemplate = file_get_contents(base_path("vendor/laravel/framework/src/Illuminate/Database/Migrations/stubs/create.stub"));
174
                $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

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

277
        /** @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...
278
        DB::table("cb_modules")->where("id", $id)->delete();
279
        DB::table("cb_menus")->where("cb_modules_id", $id)->delete();
280
        return cb()->redirectBack("The module has been deleted!","success");
281
    }
282
283
    public function getDeleteSoft($id) {
284
        $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...
285
        DB::table("cb_modules")->where("id", $id)->delete();
286
        DB::table("cb_menus")->where("cb_modules_id", $id)->delete();
287
        return cb()->redirectBack("The module has been deleted!","success");
288
    }
289
290
}