Passed
Push — master ( 70a641...ae871b )
by Richard
34:57
created

ViewGenerator::generateFields()   D

Complexity

Conditions 14
Paths 244

Size

Total Lines 90
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 56
c 3
b 0
f 1
dl 0
loc 90
rs 4.8833
cc 14
nc 244
nop 0

How to fix   Long Method    Complexity   

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 PWWEB\Artomator\Generators\Scaffold;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Str;
7
use InfyOm\Generator\Generators\BaseGenerator;
8
use InfyOm\Generator\Utils\FileUtil;
9
use InfyOm\Generator\Utils\HTMLFieldGenerator;
10
use PWWEB\Artomator\Common\CommandData;
11
use PWWEB\Artomator\Generators\ViewServiceProviderGenerator;
12
13
class ViewGenerator extends BaseGenerator
14
{
15
    /** @var CommandData */
16
    private $commandData;
17
18
    /** @var string */
19
    private $path;
20
21
    /** @var string */
22
    private $templateType;
23
24
    /** @var array */
25
    private $htmlFields;
26
27
    public function __construct(CommandData $commandData)
28
    {
29
        $this->commandData = $commandData;
30
        $this->path = $commandData->config->pathViews;
31
        $this->templateType = config('infyom.laravel_generator.templates', 'adminlte-templates');
32
    }
33
34
    public function generate()
35
    {
36
        if (! file_exists($this->path)) {
37
            mkdir($this->path, 0755, true);
38
        }
39
40
        $htmlInputs = Arr::pluck($this->commandData->fields, 'htmlInput');
41
        if (in_array('file', $htmlInputs)) {
42
            $this->commandData->addDynamicVariable('$FILES$', ", 'files' => true");
43
        }
44
45
        $this->commandData->commandComment("\nGenerating Views...");
46
47
        if ($this->commandData->getOption('views')) {
48
            $viewsToBeGenerated = explode(',', $this->commandData->getOption('views'));
0 ignored issues
show
Bug introduced by
It seems like $this->commandData->getOption('views') can also be of type false; however, parameter $string of explode() 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

48
            $viewsToBeGenerated = explode(',', /** @scrutinizer ignore-type */ $this->commandData->getOption('views'));
Loading history...
49
50
            if (in_array('index', $viewsToBeGenerated)) {
51
                $this->generateTable();
52
                $this->generateIndex();
53
            }
54
55
            if (count(array_intersect(['create', 'update'], $viewsToBeGenerated)) > 0) {
56
                $this->generateFields();
57
            }
58
59
            if (in_array('create', $viewsToBeGenerated)) {
60
                $this->generateCreate();
61
            }
62
63
            if (in_array('edit', $viewsToBeGenerated)) {
64
                $this->generateUpdate();
65
            }
66
67
            if (in_array('show', $viewsToBeGenerated)) {
68
                $this->generateShowFields();
69
                $this->generateShow();
70
            }
71
        } else {
72
            $this->generateTable();
73
            $this->generateIndex();
74
            $this->generateFields();
75
            $this->generateCreate();
76
            $this->generateUpdate();
77
            $this->generateShowFields();
78
            $this->generateShow();
79
        }
80
81
        $this->commandData->commandComment('Views created: ');
82
    }
83
84
    private function generateTable()
85
    {
86
        if ($this->commandData->getAddOn('datatables')) {
87
            $templateData = $this->generateDataTableBody();
88
            $this->generateDataTableActions();
89
        } else {
90
            $templateData = $this->generateBladeTableBody();
91
        }
92
93
        FileUtil::createFile($this->path, 'table.blade.php', $templateData);
94
95
        $this->commandData->commandInfo('table.blade.php created');
96
    }
97
98
    private function generateDataTableBody()
99
    {
100
        $templateData = get_artomator_template('scaffold.views.datatable_body');
101
102
        return fill_template($this->commandData->dynamicVars, $templateData);
103
    }
104
105
    private function generateDataTableActions()
106
    {
107
        $templateName = 'datatables_actions';
108
109
        if ($this->commandData->isLocalizedTemplates()) {
110
            $templateName .= '_locale';
111
        }
112
113
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
114
115
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
116
117
        FileUtil::createFile($this->path, 'datatables_actions.blade.php', $templateData);
118
119
        $this->commandData->commandInfo('datatables_actions.blade.php created');
120
    }
121
122
    private function generateBladeTableBody()
123
    {
124
        $templateName = 'blade_table_body';
125
126
        if ($this->commandData->isLocalizedTemplates()) {
127
            $templateName .= '_locale';
128
        }
129
130
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
131
132
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
133
134
        $templateData = str_replace('$FIELD_HEADERS$', $this->generateTableHeaderFields(), $templateData);
135
136
        $cellFieldTemplate = get_artomator_template('scaffold.views.table_cell');
137
138
        $tableBodyFields = [];
139
140
        foreach ($this->commandData->fields as $field) {
141
            if (! $field->inIndex) {
142
                continue;
143
            }
144
145
            $tableBodyFields[] = fill_template_with_field_data(
146
                $this->commandData->dynamicVars,
147
                $this->commandData->fieldNamesMapping,
148
                $cellFieldTemplate,
149
                $field
150
            );
151
        }
152
153
        $tableBodyFields = implode(infy_nl_tab(1, 3), $tableBodyFields);
154
155
        return str_replace('$FIELD_BODY$', $tableBodyFields, $templateData);
156
    }
157
158
    private function generateTableHeaderFields()
159
    {
160
        $templateName = 'table_header';
161
162
        $localized = false;
163
        if ($this->commandData->isLocalizedTemplates()) {
164
            $templateName .= '_locale';
165
            $localized = true;
166
        }
167
168
        $headerFieldTemplate = get_artomator_template('scaffold.views.'.$templateName);
169
170
        $headerFields = [];
171
172
        foreach ($this->commandData->fields as $field) {
173
            if (! $field->inIndex) {
174
                continue;
175
            }
176
177
            if ($localized) {
178
                $headerFields[] = $fieldTemplate = fill_template_with_field_data_locale(
0 ignored issues
show
Unused Code introduced by
The assignment to $fieldTemplate is dead and can be removed.
Loading history...
179
                    $this->commandData->dynamicVars,
180
                    $this->commandData->fieldNamesMapping,
181
                    $headerFieldTemplate,
182
                    $field
183
                );
184
            } else {
185
                $headerFields[] = $fieldTemplate = fill_template_with_field_data(
186
                    $this->commandData->dynamicVars,
187
                    $this->commandData->fieldNamesMapping,
188
                    $headerFieldTemplate,
189
                    $field
190
                );
191
            }
192
        }
193
194
        return implode(infy_nl_tab(1, 2), $headerFields);
195
    }
196
197
    private function generateIndex()
198
    {
199
        $templateName = 'index';
200
201
        if ($this->commandData->isLocalizedTemplates()) {
202
            $templateName .= '_locale';
203
        }
204
205
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
206
207
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
208
209
        if ($this->commandData->getAddOn('datatables')) {
210
            $templateData = str_replace('$PAGINATE$', '', $templateData);
211
        } else {
212
            $paginate = $this->commandData->getOption('paginate');
213
214
            if ($paginate) {
215
                $paginateTemplate = get_artomator_template('scaffold.views.paginate');
216
217
                $paginateTemplate = fill_template($this->commandData->dynamicVars, $paginateTemplate);
218
219
                $templateData = str_replace('$PAGINATE$', $paginateTemplate, $templateData);
220
            } else {
221
                $templateData = str_replace('$PAGINATE$', '', $templateData);
222
            }
223
        }
224
225
        FileUtil::createFile($this->path, 'index.blade.php', $templateData);
226
227
        $this->commandData->commandInfo('index.blade.php created');
228
    }
229
230
    private function generateFields()
231
    {
232
        $templateName = 'fields';
233
234
        $localized = false;
235
        if ($this->commandData->isLocalizedTemplates()) {
236
            $templateName .= '_locale';
237
            $localized = true;
238
        }
239
240
        $this->htmlFields = [];
241
242
        foreach ($this->commandData->fields as $field) {
243
            if (! $field->inForm) {
244
                continue;
245
            }
246
247
            $validations = explode('|', $field->validations);
248
            $minMaxRules = '';
249
            foreach ($validations as $validation) {
250
                if (! Str::contains($validation, ['max:', 'min:'])) {
251
                    continue;
252
                }
253
254
                $validationText = substr($validation, 0, 3);
255
                $sizeInNumber = substr($validation, 4);
256
257
                $sizeText = ('min' == $validationText) ? 'minlength' : 'maxlength';
258
                if ('number' == $field->htmlType) {
259
                    $sizeText = $validationText;
260
                }
261
262
                $size = ",'$sizeText' => $sizeInNumber";
263
                $minMaxRules .= $size;
264
            }
265
266
            $this->commandData->addDynamicVariable('$SIZE$', $minMaxRules);
267
268
            $required = '';
269
            if (Str::contains($validations, 'required')) {
0 ignored issues
show
Bug introduced by
$validations of type string[] is incompatible with the type string expected by parameter $haystack of Illuminate\Support\Str::contains(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

269
            if (Str::contains(/** @scrutinizer ignore-type */ $validations, 'required')) {
Loading history...
270
                $required = ',\'required\' => true';
271
            }
272
            $this->commandData->addDynamicVariable('$REQUIRED$', $required);
273
274
            $fieldTemplate = HTMLFieldGenerator::generateHTML($field, $this->templateType, $localized);
275
276
            if ('selectTable' == $field->htmlType) {
277
                $inputArr = explode(',', $field->htmlValues[1]);
278
                $columns = '';
279
                foreach ($inputArr as $item) {
280
                    $columns .= "'$item'".',';  //e.g 'email,id,'
281
                }
282
                $columns = substr_replace($columns, '', -1); // remove last ,
283
284
                $htmlValues = explode(',', $field->htmlValues[0]);
285
                $selectTable = $htmlValues[0];
286
                $modalName = null;
287
                if (2 == count($htmlValues)) {
288
                    $modalName = $htmlValues[1];
289
                }
290
291
                $tableName = $this->commandData->config->tableName;
292
                $viewPath = $this->commandData->config->prefixes['view'];
293
                if (! empty($viewPath)) {
294
                    $tableName = $viewPath.'.'.$tableName;
295
                }
296
297
                $variableName = Str::singular($selectTable).'Items'; // e.g $userItems
298
299
                $fieldTemplate = $this->generateViewComposer($tableName, $variableName, $columns, $selectTable, $modalName);
300
            }
301
302
            if (! empty($fieldTemplate)) {
303
                $fieldTemplate = fill_template_with_field_data(
304
                    $this->commandData->dynamicVars,
305
                    $this->commandData->fieldNamesMapping,
306
                    $fieldTemplate,
307
                    $field
308
                );
309
                $this->htmlFields[] = $fieldTemplate;
310
            }
311
        }
312
313
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
314
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
315
316
        $templateData = str_replace('$FIELDS$', implode("\n\n", $this->htmlFields), $templateData);
317
318
        FileUtil::createFile($this->path, 'fields.blade.php', $templateData);
319
        $this->commandData->commandInfo('field.blade.php created');
320
    }
321
322
    private function generateViewComposer($tableName, $variableName, $columns, $selectTable, $modelName = null)
323
    {
324
        $templateName = 'scaffold.fields.select';
325
        if ($this->commandData->isLocalizedTemplates()) {
326
            $templateName .= '_locale';
327
        }
328
        $fieldTemplate = get_artomator_template($templateName);
329
330
        $viewServiceProvider = new ViewServiceProviderGenerator($this->commandData);
331
        $viewServiceProvider->generate();
332
        $viewServiceProvider->addViewVariables($tableName.'.fields', $variableName, $columns, $selectTable, $modelName);
333
334
        $fieldTemplate = str_replace(
335
            '$INPUT_ARR$',
336
            '$'.$variableName,
337
            $fieldTemplate
338
        );
339
340
        return $fieldTemplate;
341
    }
342
343
    private function generateCreate()
344
    {
345
        $templateName = 'create';
346
347
        if ($this->commandData->isLocalizedTemplates()) {
348
            $templateName .= '_locale';
349
        }
350
351
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
352
353
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
354
355
        FileUtil::createFile($this->path, 'create.blade.php', $templateData);
356
        $this->commandData->commandInfo('create.blade.php created');
357
    }
358
359
    private function generateUpdate()
360
    {
361
        $templateName = 'edit';
362
363
        if ($this->commandData->isLocalizedTemplates()) {
364
            $templateName .= '_locale';
365
        }
366
367
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
368
369
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
370
371
        FileUtil::createFile($this->path, 'edit.blade.php', $templateData);
372
        $this->commandData->commandInfo('edit.blade.php created');
373
    }
374
375
    private function generateShowFields()
376
    {
377
        $templateName = 'show_field';
378
        if ($this->commandData->isLocalizedTemplates()) {
379
            $templateName .= '_locale';
380
        }
381
        $fieldTemplate = get_artomator_template('scaffold.views.'.$templateName);
382
383
        $fieldsStr = '';
384
385
        foreach ($this->commandData->fields as $field) {
386
            if (! $field->inView) {
387
                continue;
388
            }
389
            $singleFieldStr = str_replace(
390
                '$FIELD_NAME_TITLE$',
391
                Str::title(str_replace('_', ' ', $field->name)),
392
                $fieldTemplate
393
            );
394
            $singleFieldStr = str_replace('$FIELD_NAME$', $field->name, $singleFieldStr);
395
            $singleFieldStr = fill_template($this->commandData->dynamicVars, $singleFieldStr);
396
397
            $fieldsStr .= $singleFieldStr."\n\n";
398
        }
399
400
        FileUtil::createFile($this->path, 'show_fields.blade.php', $fieldsStr);
401
        $this->commandData->commandInfo('show_fields.blade.php created');
402
    }
403
404
    private function generateShow()
405
    {
406
        $templateName = 'show';
407
408
        if ($this->commandData->isLocalizedTemplates()) {
409
            $templateName .= '_locale';
410
        }
411
412
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
413
414
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
415
416
        FileUtil::createFile($this->path, 'show.blade.php', $templateData);
417
        $this->commandData->commandInfo('show.blade.php created');
418
    }
419
420
    public function rollback($views = [])
421
    {
422
        $files = [
423
            'table.blade.php',
424
            'index.blade.php',
425
            'fields.blade.php',
426
            'create.blade.php',
427
            'edit.blade.php',
428
            'show.blade.php',
429
            'show_fields.blade.php',
430
        ];
431
432
        if (! empty($views)) {
433
            $files = [];
434
            foreach ($views as $view) {
435
                $files[] = $view.'.blade.php';
436
            }
437
        }
438
439
        if ($this->commandData->getAddOn('datatables')) {
440
            $files[] = 'datatables_actions.blade.php';
441
        }
442
443
        foreach ($files as $file) {
444
            if ($this->rollbackFile($this->path, $file)) {
445
                $this->commandData->commandComment($file.' file deleted');
446
            }
447
        }
448
    }
449
}
450