Passed
Pull Request — master (#1108)
by Iman
07:29
created

Step3Handler::setFormScript()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 26
nc 4
nop 1
dl 0
loc 37
rs 8.5806
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\Modules\ModuleGenerator;
4
5
use crocodicstudio\crudbooster\helpers\Parsers\ScaffoldingParser;
6
use CRUDBooster;
0 ignored issues
show
Bug introduced by
The type CRUDBooster was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Illuminate\Support\Facades\Request;
8
9
class Step3Handler
10
{
11
    public function showForm($id)
12
    {
13
        $row = ModulesRepo::find($id);;
14
15
        $columns = CRUDBooster::getTableColumns($row->table_name);
16
17
        $code = FileManipulator::readCtrlContent($row->controller);
18
19
        $forms = ScaffoldingParser::parse($code, 'form');
20
21
        $types = $this->getComponentTypes();
22
23
        return view('CbModulesGen::step3', compact('columns', 'forms', 'types', 'id'));
24
    }
25
26
    /**
27
     * @return array
28
     */
29
    private function getComponentTypes()
30
    {
31
        $types = [];
32
        foreach (glob(CB::componentsPath().'*', GLOB_ONLYDIR) as $dir) {
33
            array_push($types, basename($dir));
34
        }
35
        return $types;
36
    }
37
38
    public function handleFormSubmit()
39
    {
40
        $scripts = $this->setFormScript(request()->all());
41
42
        $controller = ModulesRepo::getControllerName(request('id'));
43
        $phpCode = FileManipulator::readCtrlContent($controller);
44
        list($top, $currentScaffold, $bottom) = FileManipulator::extractBetween($phpCode, "FORM");
45
46
        //IF FOUND OLD, THEN CLEAR IT
47
        $bottom = $this->clearOldBackup($bottom);
48
49
        //ARRANGE THE FULL SCRIPT
50
        $fileContent = $top."\n\n";
51
        $fileContent .= str_repeat(' ', 12)."# START FORM DO NOT REMOVE THIS LINE\n";
52
        $fileContent .= $scripts;
53
        $fileContent .= "\n".str_repeat(' ', 12)."# END FORM DO NOT REMOVE THIS LINE\n\n";
54
55
        //CREATE A BACKUP SCAFFOLDING TO OLD TAG
56
        if ($currentScaffold) {
57
            $fileContent = $this->backupOldTagScaffold($fileContent, $currentScaffold);
58
        }
59
60
        $fileContent .= str_repeat(' ', 12).($bottom);
61
62
        //CREATE FILE CONTROLLER
63
        FileManipulator::putCtrlContent($controller, $fileContent);
64
65
        return redirect()->route('AdminModulesControllerGetStep4', ['id' => request('id')]);
66
    }
67
68
    /**
69
     * @param $post
70
     * @return array
71
     */
72
    private function setFormScript($post)
73
    {
74
        $name = $post['name'];
75
        $width = $post['width'];
76
        $type = $post['type'];
77
        $help = $post['help'];
78
        $placeholder = $post['placeholder'];
79
        $style = $post['style'];
80
        $validation = $post['validation'];
81
82
        $scriptForm = [];
83
        $scriptForm[] = str_repeat(' ', 12).'$this->form = [];';
84
85
        foreach ($post['label'] as $i => $label) {
86
            if ($label == '') {
87
                continue;
88
            }
89
            $form = [
90
                'label' => $label,
91
                'name' => $name[$i],
92
                'type' => $type[$i],
93
                'validation' => $validation[$i],
94
                'width' => $width[$i],
95
                'placeholder' => $placeholder[$i],
96
                'help' => $help[$i],
97
                'style' => $style[$i],
98
            ];
99
100
            $info = json_decode(file_get_contents(CRUDBooster::componentsPath($type[$i]).'/info.json'), true);
101
            if (!empty($info['options'])) {
102
                $form = $this->parseComponentOptions($post, $info, $form);
103
            }
104
105
            $scriptForm[] = str_repeat(' ', 12).'$this->form[] = '.FileManipulator::stringify($form, str_repeat(' ', 12)).';';
106
        }
107
108
        return implode("\n", $scriptForm);
0 ignored issues
show
Bug Best Practice introduced by
The expression return implode(' ', $scriptForm) returns the type string which is incompatible with the documented return type array.
Loading history...
109
    }
110
111
    /**
112
     * @param $bottomScript
113
     * @return mixed
114
     */
115
    private function clearOldBackup($bottomScript)
116
    {
117
        if (strpos($bottomScript, '# OLD START FORM') === false) {
118
            return $bottomScript;
119
        }
120
        $lineStart = strpos($bottomScript, '# OLD START FORM');
121
        $lineEnd = strpos($bottomScript, '# OLD END FORM') + strlen('# OLD END FORM');
122
123
        $getString = substr($bottomScript, $lineStart, $lineEnd);
124
125
        return str_replace($getString, '', $bottomScript);
126
    }
127
128
    /**
129
     * @param $fileContent
130
     * @param $middle
131
     * @return string
132
     */
133
    private function backupOldTagScaffold($fileContent, $middle)
134
    {
135
        $middle = preg_split("/\\r\\n|\\r|\\n/", $middle);
136
        foreach ($middle as &$c) {
137
            $c = "            //".trim($c);
138
        }
139
        $middle = implode("\n", $middle);
0 ignored issues
show
Bug introduced by
It seems like $middle can also be of type false; however, parameter $pieces of implode() does only seem to accept array, 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

139
        $middle = implode("\n", /** @scrutinizer ignore-type */ $middle);
Loading history...
140
141
        $fileContent .= str_repeat(' ', 12)."# OLD START FORM\n";
142
        $fileContent .= $middle."\n";
143
        $fileContent .= str_repeat(' ', 12)."# OLD END FORM\n\n";
144
145
        return $fileContent;
146
    }
147
148
    /**
149
     * @param $post
150
     * @param $info
151
     * @param $form
152
     * @return array
153
     */
154
    private function parseComponentOptions($post, $info, $form)
155
    {
156
        $options = [];
157
        foreach ($info['options'] as $i => $opt) {
158
            $optionValue = $post[$opt['name']][$form['name']];
159
            if ($opt['type'] == 'array') {
160
                $options[$opt['name']] = ($optionValue) ? explode(";", $optionValue) : [];
161
            } elseif ($opt['type'] == 'boolean') {
162
                $options[$opt['name']] = ($optionValue == 1) ? true : false;
163
            }
164
        }
165
        $form['options'] = $options;
166
167
        return $form;
168
    }
169
}