Passed
Pull Request — master (#1113)
by Iman
06:46 queued 03:01
created

FormConfigGenerator::generateFormConfig()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 80
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 56
nc 5
nop 2
dl 0
loc 80
rs 8.4041
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
namespace crocodicstudio\crudbooster\Modules\ModuleGenerator\ControllerGenerator;
4
5
use crocodicstudio\crudbooster\helpers\DbInspector;
6
use crocodicstudio\crudbooster\Modules\ModuleGenerator\FileManipulator;
7
use Illuminate\Support\Facades\Schema;
8
use CB;
9
10
class FormConfigGenerator
11
{
12
    /**
13
     * @param $table
14
     * @param $coloms
15
     * @return array
16
     */
17
    static function generateFormConfig($table, $coloms)
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...
18
    {
19
        $formArrayString = [];
20
        foreach ($coloms as $i => $colName) {
21
            //$attribute = [];
22
            $input = [
23
                'label' => self::getLabel($colName),
24
                'name' => $colName,
25
                'type' => '',
26
                'options' => '',
27
                'required' => true,
28
                'validation' => '',
29
                'help' => '',
30
                'placeholder' => '',
31
            ];
32
33
            if (FieldDetector::isExceptional($colName)) {
34
                continue;
35
            }
36
37
            $typeData = DbInspector::getFieldTypes($table, $colName);
38
39
            list($input['type'], $input['validation'], $input['options']) = self::parseFieldType($typeData);
40
41
            if (FieldDetector::isForeignKey($colName)) {
42
                list($input['type'], $input['options']) = self::handleForeignKey($colName);
43
            } elseif (substr($colName, 0, 3) == 'is_') {
44
                $input['type'] = 'radio_dataenum';
45
                $label = ucwords(substr($colName, 3));
46
                $input['options'] = [
47
                    'enum' => ['In '.$label, $label],
48
                    'value' => [0, 1],
49
                ];
50
            }
51
52
            $map = [
53
                'password' => [
54
                    'type' => 'password',
55
                    'validation' => 'min:5|max:32|required',
56
                    'help' => cbTrans("text_default_help_password"),
57
                ],
58
                'image' => [
59
                    'type' => 'upload',
60
                    'validation' => 'required|image',
61
                    'help' => cbTrans('text_default_help_upload'),
62
                ],
63
                'geo' => [
64
                    'type' => 'hidden',
65
                    'validation' => 'required|numeric',
66
                ],
67
                'phone' => [
68
                    'type' => 'number',
69
                    'validation' => 'required|numeric',
70
                    'placeholder' => cbTrans('text_default_help_number'),
71
                ],
72
                'email' => [
73
                    'type' => 'email',
74
                    'validation' => 'require|email|unique:'.$table,
75
                    'placeholder' => cbTrans('text_default_help_email'),
76
                ],
77
                'name' => [
78
                    'type' => 'text',
79
                    'validation' => 'required|string|min:3|max:70',
80
                    'placeholder' => cbTrans('text_default_help_text'),
81
                ],
82
                'url' => [
83
                    'type' => 'text',
84
                    'validation' => 'required|url',
85
                    'placeholder' => cbTrans('text_default_help_url'),
86
                ],
87
            ];
88
            
89
            $props = array_get($map, FieldDetector::detect($colName));
90
            unset($map);
91
            $input = array_merge($input, $props);
92
93
            $formArrayString[] = FileManipulator::stringify($input, str_repeat(" ", 12));
94
        }
95
96
        return $formArrayString;
97
    }
98
99
    /**
100
     * @param $c
101
     * @return mixed|string
102
     */
103
    private static function getLabel($c)
104
    {
105
        $label = str_replace("id_", "", $c);
106
        $label = ucwords(str_replace("_", " ", $label));
107
108
        return $label;
109
    }
110
111
    /**
112
     * @param $typeData
113
     *
114
     * @return array
115
     */
116
    private static function parseFieldType($typeData)
117
    {
118
        // if matched a key, overrides $typeData to corresponding values
119
        $typeData = array_get([
120
            'longtext' => 'text',
121
            'integer' => 'int',
122
            'timestamp' => 'datetime',
123
        ], $typeData, $typeData);
124
125
        $default = ["text", "min:1|max:255", []];
126
127
        return array_get([
128
            'text' => ['textarea', "string|min:5", []],
129
            'date' => ['date', "date", ['php_format' => 'M, d Y', 'datepicker_format' => 'M, dd YYYY',]],
130
            'datetime' => ['datetime', "date_format:Y-m-d H:i:s", ['php_format' => 'M, d Y H:i',]],
131
            'time' => ['time', 'date_format:H:i:s', []],
132
            'double' => ['money', "integer|min:0", []],
133
            'int' => ['number', 'integer|min:0', []],
134
        ], $typeData, $default);
0 ignored issues
show
Bug introduced by
It seems like $typeData can also be of type array<string,string>; however, parameter $key of array_get() 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

134
        ], /** @scrutinizer ignore-type */ $typeData, $default);
Loading history...
135
    }
136
137
    /**
138
     * @param $field
139
     * @return array
140
     */
141
    private static function handleForeignKey($field)
142
    {
143
        $jointable = str_replace(['id_', '_id'], '', $field);
144
        if (! Schema::hasTable($jointable)) {
145
            return ['', ''];
146
        }
147
        $options = [
148
            'table' => $jointable,
149
            'field_label' => DbInspector::colName(DbInspector::getTableCols($jointable)),
150
            'field_value' => DbInspector::findPk($jointable),
151
        ];
152
153
        return ['select2_datatable', $options];
154
    }
155
}