Passed
Push — master ( 3388c8...01e728 )
by Iman
08:15 queued 02:52
created

Step3Handler::parseComponentOptions()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 6
nop 3
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\Modules\ModuleGenerator;
4
5
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...
6
7
class Step3Handler
8
{
9
    public function showForm($id)
10
    {
11
        $row = ModulesRepo::find($id);;
12
13
        $columns = CRUDBooster::getTableColumns($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(CB::componentsPath().'*', 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
        $fileContent .= str_repeat(' ', 12)."# START FORM DO NOT REMOVE THIS LINE\n";
50
        $fileContent .= $scripts;
51
        $fileContent .= "\n".str_repeat(' ', 12)."# END FORM DO NOT REMOVE THIS LINE\n\n";
52
53
        //CREATE A BACKUP SCAFFOLDING TO OLD TAG
54
        if ($currentScaffold) {
55
            $fileContent = $this->backupOldTagScaffold($fileContent, $currentScaffold);
56
        }
57
58
        $fileContent .= str_repeat(' ', 12).($bottom);
59
60
        //CREATE FILE CONTROLLER
61
        FileManipulator::putCtrlContent($controller, $fileContent);
62
63
        return redirect()->route('AdminModulesControllerGetStep4', ['id' => request('id')]);
64
    }
65
66
    /**
67
     * @param $post
68
     * @return array
69
     */
70
    private function setFormScript($post)
71
    {
72
        $name = $post['name'];
73
        $width = $post['width'];
74
        $type = $post['type'];
75
        $help = $post['help'];
76
        $placeholder = $post['placeholder'];
77
        $style = $post['style'];
78
        $validation = $post['validation'];
79
80
        $scriptForm = [];
81
        $scriptForm[] = str_repeat(' ', 12).'$this->form = [];';
82
83
        foreach ($post['label'] as $i => $label) {
84
            if ($label == '') {
85
                continue;
86
            }
87
            $form = [
88
                'label' => $label,
89
                'name' => $name[$i],
90
                'type' => $type[$i],
91
                'validation' => $validation[$i],
92
                'width' => $width[$i],
93
                'placeholder' => $placeholder[$i],
94
                'help' => $help[$i],
95
                'style' => $style[$i],
96
            ];
97
98
            $info = json_decode(file_get_contents(CRUDBooster::componentsPath($type[$i]).'/info.json'), true);
99
            if (!empty($info['options'])) {
100
                $form = $this->parseComponentOptions($post, $info, $form);
101
            }
102
103
            $scriptForm[] = str_repeat(' ', 12).'$this->form[] = '.FileManipulator::stringify($form, str_repeat(' ', 12)).';';
104
        }
105
106
        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...
107
    }
108
109
    /**
110
     * @param $bottomScript
111
     * @return mixed
112
     */
113
    private function clearOldBackup($bottomScript)
114
    {
115
        if (strpos($bottomScript, '# OLD START FORM') === false) {
116
            return $bottomScript;
117
        }
118
        $lineStart = strpos($bottomScript, '# OLD START FORM');
119
        $lineEnd = strpos($bottomScript, '# OLD END FORM') + strlen('# OLD END FORM');
120
121
        $getString = substr($bottomScript, $lineStart, $lineEnd);
122
123
        return str_replace($getString, '', $bottomScript);
124
    }
125
126
    /**
127
     * @param $fileContent
128
     * @param $middle
129
     * @return string
130
     */
131
    private function backupOldTagScaffold($fileContent, $middle)
132
    {
133
        $middle = preg_split("/\\r\\n|\\r|\\n/", $middle);
134
        foreach ($middle as &$c) {
135
            $c = str_repeat(' ', 12)."//".trim($c);
136
        }
137
        $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

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