Passed
Push — master ( 66edb2...57cab0 )
by Richard
05:23
created

ViewGenerator::generateFields()   C

Complexity

Conditions 14
Paths 204

Size

Total Lines 92
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

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