Passed
Push — master ( 62919d...1f65fa )
by Iman
04:23
created

Step3Handler::setFormScript()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 40
rs 9.28
c 0
b 0
f 0
1
<?php
2
3
namespace Crocodicstudio\Crudbooster\Modules\ModuleGenerator;
4
5
use CB;
0 ignored issues
show
Bug introduced by
The type CB 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...
6
7
class Step3Handler
8
{
9
    public function showForm($id)
10
    {
11
        $row = ModulesRepo::find($id);;
12
13
        $columns = \Schema::getColumnListing($row->table_name);
14
15
        $code = FileManipulator::readCtrlContent($row->controller);
16
17
        $forms = ScaffoldingParser::parse($code, 'form');
18
19
        $types = $this->getComponentTypes();
20
21
        return view('CbModulesGen::step3', compact('columns', 'forms', 'types', 'id'));
22
    }
23
24
    /**
25
     * @return array
26
     */
27
    private function getComponentTypes()
28
    {
29
        $types = [];
30
        foreach (glob(CbComponentsPath().'*', GLOB_ONLYDIR) as $dir) {
31
            array_push($types, basename($dir));
32
        }
33
        return $types;
34
    }
35
36
    public function handleFormSubmit()
37
    {
38
        $scripts = $this->setFormScript(request()->all());
39
40
        $controller = ModulesRepo::getControllerName(request('id'));
41
        $phpCode = FileManipulator::readCtrlContent($controller);
42
        list($top, $currentScaffold, $bottom) = FileManipulator::extractBetween($phpCode, "FORM");
43
44
        //IF FOUND OLD, THEN CLEAR IT
45
        $bottom = $this->clearOldBackup($bottom);
46
47
        //ARRANGE THE FULL SCRIPT
48
        $fileContent = $top."\n\n";
49
        $indent = str_repeat(' ', 8);
50
        $fileContent .= $indent.cbStartMarker("FORM")."\n";
51
        $fileContent .= $scripts;
52
        $fileContent .= "\n".$indent.cbEndMarker('FORM')."\n\n";
53
54
        //CREATE A BACKUP SCAFFOLDING TO OLD TAG
55
        if ($currentScaffold) {
56
            $fileContent = $this->backupOldTagScaffold($fileContent, $currentScaffold);
57
        }
58
59
        $fileContent .= $indent.($bottom);
60
61
        //CREATE FILE CONTROLLER
62
        FileManipulator::putCtrlContent($controller, $fileContent);
63
64
        return redirect()->route('AdminModulesControllerGetStep4', ['id' => request('id')]);
65
    }
66
67
    /**
68
     * @param $post
69
     * @return array
70
     */
71
    private function setFormScript($post)
72
    {
73
        $name = $post['name'];
74
        $width = $post['width'];
75
        $type = $post['type'];
76
        $help = $post['help'];
77
        $placeholder = $post['placeholder'];
78
        $style = $post['style'];
79
        $validation = $post['validation'];
80
81
        $scriptForm = [];
82
83
        $indent = str_repeat(' ', 8);
84
85
        $scriptForm[] = $indent.'$this->form = [];';
86
87
        foreach ($post['label'] as $i => $label) {
88
            if ($label == '') {
89
                continue;
90
            }
91
            $form = [
92
                'label' => $label,
93
                'name' => $name[$i],
94
                'type' => $type[$i],
95
                'validation' => $validation[$i],
96
                'width' => $width[$i],
97
                'placeholder' => $placeholder[$i],
98
                'help' => $help[$i],
99
                'style' => $style[$i],
100
            ];
101
102
            $info = json_decode(file_get_contents(CbComponentsPath($type[$i]).'/info.json'), true);
103
            if (!empty($info['options'])) {
104
                $form = $this->parseComponentOptions($post, $info, $form);
105
            }
106
107
            $scriptForm[] = $indent.'$this->form[] = '.FileManipulator::stringify($form, $indent).';';
108
        }
109
110
        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...
111
    }
112
113
    /**
114
     * @param $bottomScript
115
     * @return mixed
116
     */
117
    private function clearOldBackup($bottomScript)
118
    {
119
        if (strpos($bottomScript, '# OLD START FORM') === false) {
120
            return $bottomScript;
121
        }
122
        $lineStart = strpos($bottomScript, '# OLD START FORM');
123
        $lineEnd = strpos($bottomScript, '# OLD END FORM') + strlen('# OLD END FORM');
124
125
        $getString = substr($bottomScript, $lineStart, $lineEnd);
126
127
        return str_replace($getString, '', $bottomScript);
128
    }
129
130
    /**
131
     * @param $fileContent
132
     * @param $middle
133
     * @return string
134
     */
135
    private function backupOldTagScaffold($fileContent, $middle)
136
    {
137
        $middle = preg_split("/\\r\\n|\\r|\\n/", $middle);
138
        foreach ($middle as &$c) {
139
            $c = str_repeat(' ', 12)."//".trim($c);
140
        }
141
        $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

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