Passed
Push — master ( 48aa9a...5ad1d2 )
by Richard
10:34
created

ViewGenerator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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