Passed
Push — master ( 38a665...decd12 )
by Ferry
05:33
created

ModuleGenerator   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 99
dl 0
loc 149
rs 8.8
c 2
b 0
f 0
wmc 45

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A makeControllerName() 0 4 1
D make() 0 126 43

How to fix   Complexity   

Complex Class

Complex classes like ModuleGenerator 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 ModuleGenerator, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: User
5
 * Date: 4/25/2019
6
 * Time: 8:14 AM
7
 */
8
9
namespace crocodicstudio\crudbooster\helpers;
10
11
12
use Illuminate\Support\Facades\DB;
13
use Illuminate\Support\Str;
14
use Illuminate\Support\Facades\Cache;
15
16
class ModuleGenerator
17
{
18
    private $table;
19
    private $icon;
20
    private $name;
21
    private $columns;
22
    private $rebuild;
23
24
    public function __construct($table, $name = null, $icon = "fa fa-bars", $columns, $rebuild = null)
25
    {
26
        $this->table = $table;
27
        $this->icon = $icon;
28
        $this->name = $name;
29
        $this->columns = $columns;
30
        $this->rebuild = $rebuild;
31
    }
32
33
    private function makeControllerName($name) {
34
        $controllerName = ucwords(str_replace('_', ' ', $name));
35
        $controllerName = str_replace(' ', '', $controllerName).'Controller';
36
        return "Admin".$controllerName;
37
    }
38
39
    public function make() {
40
        $name = trim(($this->name)?:ucwords(str_replace("_"," ",$this->table)));
41
42
        $template = file_get_contents(__DIR__."/../templates/FooBarController.stub");
43
44
        //Replace table
45
        $template = str_replace("{table}",'"'.$this->table.'"', $template);
46
47
        //Replace permalink
48
        $permalink = strtolower(Str::slug($name,"_"));
49
        $template = str_replace("{permalink}", '"'.$permalink.'"', $template);
50
51
        //Replace Page title
52
        $template = str_replace("{page_title}", '"'.$name.'"', $template);
53
54
        //Replace scaffolding
55
        $scaffold = "";
56
        foreach($this->columns as $field) {
57
            $label = $field['column_label'];
58
            $column = $field['column_field'];
59
            $help = isset($field['column_help'])?"->help(\"".$field['column_help']."\")":"";
60
            $required = ($field['column_mandatory']=="on")?"":"->required(false)";
61
            $indexShow = ($field['column_browse']=="on")?"":"->showIndex(false)";
62
            $detailShow = ($field['column_detail']=="on")?"":"->showDetail(false)";
63
            $editShow = ($field['column_edit']=="on")?"":"->showEdit(false)";
64
            $addShow = ($field['column_add']=="on")?"":"->showAdd(false)";
65
            $optionTable = $field['column_option_table'];
66
            $optionValue = $field['column_option_value'];
67
            $optionDisplay = $field['column_option_display'];
68
            $optionSqlCondition = $field['column_option_sql_condition'];
69
            $optionSqlCondition = str_replace('"',"'", $optionSqlCondition);
70
            $sqlRawQuery = $field['column_sql_query'];
71
            $options = $field['column_options'];
72
            $imageResizeWidth = $field['column_image_width'];
73
            $imageResizeHeight = $field['column_image_height'];
74
            $fileEncrypt = $field['column_file_encrypt'];
75
            $dateFormat = $field['column_date_format'];
76
            $textDisplayLimit = $field['column_text_display_limit'];
77
            $maxCharacter = $field['column_text_max'];
78
            $minCharacter = $field['column_text_min'];
79
            $moneyPrefix = $field['column_money_prefix'];
80
            $moneyPrecision = $field['column_money_precision'];
81
            $moneyThousandSeparator = $field['column_money_thousand_separator'];
82
            $moneyDecimalSeparator = $field['column_money_decimal_separator'];
83
84
            // Additional Attributes
85
            $additional = $required . $indexShow . $detailShow . $addShow . $editShow . $help ;
86
87
            // Additional money
88
            $additional .= ($moneyPrefix && $field['column_type']=='money')?"->prefix('".$moneyPrefix."')":"";
89
            $additional .= ($moneyPrecision && $field['column_type']=='money')?"->precision('".$moneyPrecision."')":"";
90
            $additional .= ($moneyThousandSeparator && $field['column_type']=='money')?"->thousandSeparator('".$moneyThousandSeparator."')":"";
91
            $additional .= ($moneyDecimalSeparator && $field['column_type']=='money')?"->decimalSeparator('".$moneyDecimalSeparator."')":"";
92
93
            // Additional for image & file type
94
            $additional .= ($fileEncrypt && in_array($field['column_type'],['file','image']))?"->encrypt(true)":"";
95
            $additional .= ($imageResizeWidth && in_array($field['column_type'],['file','image']))?"->resize(".$imageResizeWidth.",".$imageResizeHeight.")":"";
96
97
            // Additional for date & datetime
98
            $additional .= ($dateFormat && in_array($field['column_type'],['date','datetime']))?"->format('".$dateFormat."')":"";
99
100
            // Additional for text
101
            $additional .= ($textDisplayLimit!="" && in_array($field['column_type'],['text','text_area','wysiwyg']))?"->strLimit(".$textDisplayLimit.")":"";
102
            $additional .= ($maxCharacter!="" && in_array($field['column_type'],['text','text_area']))?"->maxLength(".$maxCharacter.")":"";
103
            $additional .= ($minCharacter!="" && in_array($field['column_type'],['text','text_area']))?"->minLength(".$minCharacter.")":"";
104
105
            $methodName = Str::studly($field['column_type']);
106
            if($label && $column) {
107
                if(in_array($field['column_type'],['radio','select_option','checkbox'])) {
108
                    if($options) {
109
                        $optResult = [];
110
                        foreach($options as $opt) {
111
                            $optResult[$opt['key']] = $opt['label'];
112
                        }
113
                        $scaffold .= '$this->add' . $methodName . '("' . $label . '","' . $column . '")->options('.min_var_export($optResult).')' . $additional . ';' . "\n\t\t";
114
                    }
115
                }elseif (in_array($field['column_type'],['radio_table','select_table'])) {
116
                    if ($optionTable && $optionValue && $optionDisplay) {
117
                        $scaffold .= '$this->add' . $methodName . '("' . $label . '","' . $column . '",["table"=>"' . $optionTable . '","value_option"=>"' . $optionValue . '","display_option"=>"' . $optionDisplay . '","sql_condition"=>"' . $optionSqlCondition . '"])' . $additional . ';' . "\n\t\t";
118
                    }
119
                }elseif ($field['column_type'] == "select_query") {
120
                    if($sqlRawQuery && Str::contains($sqlRawQuery,["as `key`","as `label`"])) {
121
                        $scaffold .= '$this->add' . $methodName . '("' . $label . '","' . $column . '","'.$sqlRawQuery.'")' . $additional . ';' . "\n\t\t";
122
                    }
123
                }else{
124
                    $scaffold .= '$this->add'.$methodName.'("'.$label.'","'.$column.'")'.$additional.';'."\n\t\t";
125
                }
126
            }
127
        }
128
        $template = str_replace("{scaffolding}", $scaffold, $template);
129
130
        $filename = $this->makeControllerName($name);
131
132
        //Replace Controller Name
133
        $template = str_replace("FooBarController", $filename, $template);
134
135
        //Create a controller file
136
        file_put_contents(app_path("Http/Controllers/".$filename.".php"), $template);
137
138
        //Save to database
139
        $module = [];
140
        $module['name'] = $name;
141
        $module['icon'] = $this->icon;
142
        $module['table_name'] = $this->table;
143
        $module['controller'] = $filename;
144
        $module['last_column_build'] = json_encode($this->columns);
145
146
        if($moduleData = DB::table("cb_modules")->where("name", $name)->where("table_name",$this->table)->first()) {
147
            DB::table("cb_modules")->where("id",$moduleData->id)->update($module);
148
            $id_modules = $moduleData->id;
149
        }else{
150
            $id_modules = DB::table('cb_modules')->insertGetId($module);
151
        }
152
153
        //Save menu
154
        $menu = [];
155
        $menu['name'] = $module['name'];
156
        $menu['type'] = 'module';
157
        $menu['cb_modules_id'] = $id_modules;
158
        if(isset($moduleData)) {
159
            DB::table("cb_menus")->where("cb_modules_id",$moduleData->id)->update($menu);
160
        }else{
161
            DB::table('cb_menus')->insertGetId($menu);
162
        }
163
164
        return $module;
165
    }
166
167
}