ViewGenerator   F
last analyzed

Complexity

Total Complexity 60

Size/Duplication

Total Lines 536
Duplicated Lines 0 %

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 60
eloc 234
c 5
b 1
f 1
dl 0
loc 536
rs 3.6

15 Methods

Rating   Name   Duplication   Size   Complexity  
A generateViewComposer() 0 19 2
A __construct() 0 5 1
A generateShow() 0 14 2
A generateDataTableBody() 0 5 1
A generateIndex() 0 31 4
B generate() 0 48 9
C generateFields() 0 94 14
A generateBladeTableBody() 0 34 4
A generateDataTableActions() 0 15 2
A generateTableHeaderFields() 0 37 5
A generateTable() 0 12 2
A generateUpdate() 0 14 2
A rollback() 0 26 6
A generateCreate() 0 14 2
A generateShowFields() 0 27 4

How to fix   Complexity   

Complex Class

Complex classes like ViewGenerator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ViewGenerator, and based on these observations, apply Extract Interface, too.

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
    /**
16
     * Command data.
17
     *
18
     * @var CommandData
19
     */
20
    private $commandData;
21
22
    /**
23
     * Path string.
24
     *
25
     * @var string
26
     */
27
    private $path;
28
29
    /**
30
     * Template Type.
31
     *
32
     * @var string
33
     */
34
    private $templateType;
35
36
    /**
37
     * HTML Fields.
38
     *
39
     * @var array
40
     */
41
    private $htmlFields;
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param CommandData $commandData Command data.
47
     */
48
    public function __construct(CommandData $commandData)
49
    {
50
        $this->commandData = $commandData;
51
        $this->path = $commandData->config->pathViews;
52
        $this->templateType = config('infyom.laravel_generator.templates', 'adminlte-templates');
53
    }
54
55
    /**
56
     * Generate files.
57
     *
58
     * @return void
59
     */
60
    public function generate()
61
    {
62
        if (false === file_exists($this->path)) {
63
            mkdir($this->path, 0755, true);
64
        }
65
66
        $htmlInputs = Arr::pluck($this->commandData->fields, 'htmlInput');
67
        if (true === in_array('file', $htmlInputs)) {
68
            $this->commandData->addDynamicVariable('$FILES$', ", 'files' => true");
69
        }
70
71
        $this->commandData->commandComment("\nGenerating Views...");
72
73
        if (true === $this->commandData->getOption('views')) {
74
            $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

74
            $viewsToBeGenerated = explode(',', /** @scrutinizer ignore-type */ $this->commandData->getOption('views'));
Loading history...
75
76
            if (true === in_array('index', $viewsToBeGenerated)) {
77
                $this->generateTable();
78
                $this->generateIndex();
79
            }
80
81
            if (count(array_intersect(['create', 'update'], $viewsToBeGenerated)) > 0) {
82
                $this->generateFields();
83
            }
84
85
            if (true === in_array('create', $viewsToBeGenerated)) {
86
                $this->generateCreate();
87
            }
88
89
            if (true === in_array('edit', $viewsToBeGenerated)) {
90
                $this->generateUpdate();
91
            }
92
93
            if (true === in_array('show', $viewsToBeGenerated)) {
94
                $this->generateShowFields();
95
                $this->generateShow();
96
            }
97
        } else {
98
            $this->generateTable();
99
            $this->generateIndex();
100
            $this->generateFields();
101
            $this->generateCreate();
102
            $this->generateUpdate();
103
            $this->generateShowFields();
104
            $this->generateShow();
105
        }
106
107
        $this->commandData->commandComment('Views created: ');
108
    }
109
110
    /**
111
     * Generate Table.
112
     *
113
     * @return void
114
     */
115
    private function generateTable()
116
    {
117
        if (true === $this->commandData->getAddOn('datatables')) {
118
            $templateData = $this->generateDataTableBody();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $templateData is correct as $this->generateDataTableBody() targeting PWWEB\Artomator\Generato...generateDataTableBody() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
119
            $this->generateDataTableActions();
120
        } else {
121
            $templateData = $this->generateBladeTableBody();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $templateData is correct as $this->generateBladeTableBody() targeting PWWEB\Artomator\Generato...enerateBladeTableBody() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
122
        }
123
124
        FileUtil::createFile($this->path, 'table.blade.php', $templateData);
125
126
        $this->commandData->commandInfo('table.blade.php created');
127
    }
128
129
    /**
130
     * Generate Data Table Body.
131
     *
132
     * @return void
133
     */
134
    private function generateDataTableBody()
135
    {
136
        $templateData = get_artomator_template('scaffold.views.datatable_body');
137
138
        return fill_template($this->commandData->dynamicVars, $templateData);
0 ignored issues
show
Bug Best Practice introduced by
The expression return fill_template($th...micVars, $templateData) returns the type string which is incompatible with the documented return type void.
Loading history...
139
    }
140
141
    /**
142
     * Generate Data Table Actions.
143
     *
144
     * @return void
145
     */
146
    private function generateDataTableActions()
147
    {
148
        $templateName = 'datatables_actions';
149
150
        if (true === $this->commandData->isLocalizedTemplates()) {
151
            $templateName .= '_locale';
152
        }
153
154
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
155
156
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
157
158
        FileUtil::createFile($this->path, 'datatables_actions.blade.php', $templateData);
159
160
        $this->commandData->commandInfo('datatables_actions.blade.php created');
161
    }
162
163
    /**
164
     * Generate Blade Table Body.
165
     *
166
     * @return void
167
     */
168
    private function generateBladeTableBody()
169
    {
170
        $templateName = 'blade_table_body';
171
172
        if (true === $this->commandData->isLocalizedTemplates()) {
173
            $templateName .= '_locale';
174
        }
175
176
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
177
178
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
179
180
        $templateData = str_replace('$FIELD_HEADERS$', $this->generateTableHeaderFields(), $templateData);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->generateTableHeaderFields() targeting PWWEB\Artomator\Generato...rateTableHeaderFields() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
$this->generateTableHeaderFields() of type void is incompatible with the type string|string[] expected by parameter $replace of str_replace(). ( Ignorable by Annotation )

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

180
        $templateData = str_replace('$FIELD_HEADERS$', /** @scrutinizer ignore-type */ $this->generateTableHeaderFields(), $templateData);
Loading history...
181
182
        $cellFieldTemplate = get_artomator_template('scaffold.views.table_cell');
183
184
        $tableBodyFields = [];
185
186
        foreach ($this->commandData->fields as $field) {
187
            if (false === $field->inIndex) {
188
                continue;
189
            }
190
191
            $tableBodyFields[] = fill_template_with_field_data(
192
                $this->commandData->dynamicVars,
193
                $this->commandData->fieldNamesMapping,
194
                $cellFieldTemplate,
195
                $field
196
            );
197
        }
198
199
        $tableBodyFields = implode(infy_nl_tab(1, 3), $tableBodyFields);
200
201
        return str_replace('$FIELD_BODY$', $tableBodyFields, $templateData);
0 ignored issues
show
Bug Best Practice introduced by
The expression return str_replace('$FIE...yFields, $templateData) returns the type string which is incompatible with the documented return type void.
Loading history...
202
    }
203
204
    /**
205
     * Generate Table Header Fields.
206
     *
207
     * @return void
208
     */
209
    private function generateTableHeaderFields()
210
    {
211
        $templateName = 'table_header';
212
213
        $localized = false;
214
        if (true === $this->commandData->isLocalizedTemplates()) {
215
            $templateName .= '_locale';
216
            $localized = true;
217
        }
218
219
        $headerFieldTemplate = get_artomator_template('scaffold.views.'.$templateName);
220
221
        $headerFields = [];
222
223
        foreach ($this->commandData->fields as $field) {
224
            if (false === $field->inIndex) {
225
                continue;
226
            }
227
228
            if (true === $localized) {
229
                $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...
230
                    $this->commandData->dynamicVars,
231
                    $this->commandData->fieldNamesMapping,
232
                    $headerFieldTemplate,
233
                    $field
234
                );
235
            } else {
236
                $headerFields[] = $fieldTemplate = fill_template_with_field_data(
237
                    $this->commandData->dynamicVars,
238
                    $this->commandData->fieldNamesMapping,
239
                    $headerFieldTemplate,
240
                    $field
241
                );
242
            }
243
        }
244
245
        return implode(infy_nl_tab(1, 2), $headerFields);
0 ignored issues
show
Bug Best Practice introduced by
The expression return implode(infy_nl_tab(1, 2), $headerFields) returns the type string which is incompatible with the documented return type void.
Loading history...
246
    }
247
248
    /**
249
     * Generate Index.
250
     *
251
     * @return void
252
     */
253
    private function generateIndex()
254
    {
255
        $templateName = 'index';
256
257
        if (true === $this->commandData->isLocalizedTemplates()) {
258
            $templateName .= '_locale';
259
        }
260
261
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
262
263
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
264
265
        if (true === $this->commandData->getAddOn('datatables')) {
266
            $templateData = str_replace('$PAGINATE$', '', $templateData);
267
        } else {
268
            $paginate = $this->commandData->getOption('paginate');
269
270
            if (true === $paginate) {
271
                $paginateTemplate = get_artomator_template('scaffold.views.paginate');
272
273
                $paginateTemplate = fill_template($this->commandData->dynamicVars, $paginateTemplate);
274
275
                $templateData = str_replace('$PAGINATE$', $paginateTemplate, $templateData);
276
            } else {
277
                $templateData = str_replace('$PAGINATE$', '', $templateData);
278
            }
279
        }
280
281
        FileUtil::createFile($this->path, 'index.blade.php', $templateData);
282
283
        $this->commandData->commandInfo('index.blade.php created');
284
    }
285
286
    /**
287
     * Generate Fields.
288
     *
289
     * @return void
290
     */
291
    private function generateFields()
292
    {
293
        $templateName = 'fields';
294
295
        $localized = false;
296
        if (true === $this->commandData->isLocalizedTemplates()) {
297
            $templateName .= '_locale';
298
            $localized = true;
299
        }
300
301
        $this->htmlFields = [];
302
303
        foreach ($this->commandData->fields as $field) {
304
            if (false === $field->inForm) {
305
                continue;
306
            }
307
308
            $validations = explode('|', $field->validations);
309
            $minMaxRules = '';
310
            $required = '';
311
            foreach ($validations as $validation) {
312
                if (false === Str::contains($validation, ['max:', 'min:'])) {
313
                    continue;
314
                }
315
316
                $validationText = substr($validation, 0, 3);
317
                $sizeInNumber = substr($validation, 4);
318
319
                $sizeText = ('min' === $validationText) ? 'minlength' : 'maxlength';
320
                if ('number' === $field->htmlType) {
321
                    $sizeText = $validationText;
322
                }
323
324
                if (true === Str::contains($validation, 'required')) {
325
                    $required = ',\'required\' => true';
326
                }
327
328
                $size = ",'$sizeText' => $sizeInNumber";
329
                $minMaxRules .= $size;
330
            }
331
332
            $this->commandData->addDynamicVariable('$SIZE$', $minMaxRules);
333
334
            $this->commandData->addDynamicVariable('$REQUIRED$', $required);
335
336
            $fieldTemplate = HTMLFieldGenerator::generateHTML($field, $this->templateType, $localized);
337
338
            if ('selectTable' === $field->htmlType) {
339
                $inputArr = explode(',', $field->htmlValues[1]);
340
                $columns = '';
341
                foreach ($inputArr as $item) {
342
                    $columns .= "'$item'".',';
343
                    //e.g 'email,id,'
344
                }
345
                $columns = substr_replace($columns, '', -1);
346
                // remove last ,
347
348
                $htmlValues = explode(',', $field->htmlValues[0]);
349
                $selectTable = $htmlValues[0];
350
                $modalName = null;
351
                if (2 === count($htmlValues)) {
352
                    $modalName = $htmlValues[1];
353
                }
354
355
                $tableName = $this->commandData->config->tableName;
356
                $viewPath = $this->commandData->config->prefixes['view'];
357
                if (false === empty($viewPath)) {
358
                    $tableName = $viewPath.'.'.$tableName;
359
                }
360
361
                $variableName = Str::singular($selectTable).'Items';
362
                // e.g $userItems
363
364
                $fieldTemplate = $this->generateViewComposer($tableName, $variableName, $columns, $selectTable, $modalName);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type array; however, parameter $columns of PWWEB\Artomator\Generato...:generateViewComposer() 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

364
                $fieldTemplate = $this->generateViewComposer($tableName, $variableName, /** @scrutinizer ignore-type */ $columns, $selectTable, $modalName);
Loading history...
Bug introduced by
Are you sure the assignment to $fieldTemplate is correct as $this->generateViewCompo...electTable, $modalName) targeting PWWEB\Artomator\Generato...:generateViewComposer() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
365
            }
366
367
            if (false === empty($fieldTemplate)) {
368
                $fieldTemplate = fill_template_with_field_data(
369
                    $this->commandData->dynamicVars,
370
                    $this->commandData->fieldNamesMapping,
371
                    $fieldTemplate,
372
                    $field
373
                );
374
                $this->htmlFields[] = $fieldTemplate;
375
            }
376
        }
377
378
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
379
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
380
381
        $templateData = str_replace('$FIELDS$', implode("\n\n", $this->htmlFields), $templateData);
382
383
        FileUtil::createFile($this->path, 'fields.blade.php', $templateData);
384
        $this->commandData->commandInfo('field.blade.php created');
385
    }
386
387
    /**
388
     * Generate View Composer.
389
     *
390
     * @param string      $tableName    Table name.
391
     * @param string      $variableName Variable name.
392
     * @param string      $columns      Column names.
393
     * @param string      $selectTable  Select table name.
394
     * @param string|null $modelName    Model name.
395
     *
396
     * @return void
397
     */
398
    private function generateViewComposer($tableName, $variableName, $columns, $selectTable, $modelName = null)
399
    {
400
        $templateName = 'scaffold.fields.select';
401
        if (true === $this->commandData->isLocalizedTemplates()) {
402
            $templateName .= '_locale';
403
        }
404
        $fieldTemplate = get_artomator_template($templateName);
405
406
        $viewServiceProvider = new ViewServiceProviderGenerator($this->commandData);
407
        $viewServiceProvider->generate();
408
        $viewServiceProvider->addViewVariables($tableName.'.fields', $variableName, $columns, $selectTable, $modelName);
409
410
        $fieldTemplate = str_replace(
411
            '$INPUT_ARR$',
412
            '$'.$variableName,
413
            $fieldTemplate
414
        );
415
416
        return $fieldTemplate;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $fieldTemplate returns the type string which is incompatible with the documented return type void.
Loading history...
417
    }
418
419
    /**
420
     * Generate Create.
421
     *
422
     * @return void
423
     */
424
    private function generateCreate()
425
    {
426
        $templateName = 'create';
427
428
        if (true === $this->commandData->isLocalizedTemplates()) {
429
            $templateName .= '_locale';
430
        }
431
432
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
433
434
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
435
436
        FileUtil::createFile($this->path, 'create.blade.php', $templateData);
437
        $this->commandData->commandInfo('create.blade.php created');
438
    }
439
440
    /**
441
     * Generate Update.
442
     *
443
     * @return void
444
     */
445
    private function generateUpdate()
446
    {
447
        $templateName = 'edit';
448
449
        if (true === $this->commandData->isLocalizedTemplates()) {
450
            $templateName .= '_locale';
451
        }
452
453
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
454
455
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
456
457
        FileUtil::createFile($this->path, 'edit.blade.php', $templateData);
458
        $this->commandData->commandInfo('edit.blade.php created');
459
    }
460
461
    /**
462
     * Generate Show Fields.
463
     *
464
     * @return void
465
     */
466
    private function generateShowFields()
467
    {
468
        $templateName = 'show_field';
469
        if (true === $this->commandData->isLocalizedTemplates()) {
470
            $templateName .= '_locale';
471
        }
472
        $fieldTemplate = get_artomator_template('scaffold.views.'.$templateName);
473
474
        $fieldsStr = '';
475
476
        foreach ($this->commandData->fields as $field) {
477
            if (false === $field->inView) {
478
                continue;
479
            }
480
            $singleFieldStr = str_replace(
481
                '$FIELD_NAME_TITLE$',
482
                Str::title(str_replace('_', ' ', $field->name)),
483
                $fieldTemplate
484
            );
485
            $singleFieldStr = str_replace('$FIELD_NAME$', $field->name, $singleFieldStr);
486
            $singleFieldStr = fill_template($this->commandData->dynamicVars, $singleFieldStr);
487
488
            $fieldsStr .= $singleFieldStr."\n\n";
489
        }
490
491
        FileUtil::createFile($this->path, 'show_fields.blade.php', $fieldsStr);
492
        $this->commandData->commandInfo('show_fields.blade.php created');
493
    }
494
495
    /**
496
     * Generate Show.
497
     *
498
     * @return void
499
     */
500
    private function generateShow()
501
    {
502
        $templateName = 'show';
503
504
        if (true === $this->commandData->isLocalizedTemplates()) {
505
            $templateName .= '_locale';
506
        }
507
508
        $templateData = get_artomator_template('scaffold.views.'.$templateName);
509
510
        $templateData = fill_template($this->commandData->dynamicVars, $templateData);
511
512
        FileUtil::createFile($this->path, 'show.blade.php', $templateData);
513
        $this->commandData->commandInfo('show.blade.php created');
514
    }
515
516
    /**
517
     * Rollback.
518
     *
519
     * @param array $views Views to rollback.
520
     *
521
     * @return void
522
     */
523
    public function rollback($views = [])
524
    {
525
        $files = [
526
            'table.blade.php',
527
            'index.blade.php',
528
            'fields.blade.php',
529
            'create.blade.php',
530
            'edit.blade.php',
531
            'show.blade.php',
532
            'show_fields.blade.php',
533
        ];
534
535
        if (false === empty($views)) {
536
            $files = [];
537
            foreach ($views as $view) {
538
                $files[] = $view.'.blade.php';
539
            }
540
        }
541
542
        if (true === $this->commandData->getAddOn('datatables')) {
543
            $files[] = 'datatables_actions.blade.php';
544
        }
545
546
        foreach ($files as $file) {
547
            if (true === $this->rollbackFile($this->path, $file)) {
548
                $this->commandData->commandComment($file.' file deleted');
549
            }
550
        }
551
    }
552
}
553