Passed
Push — master ( 6e1263...e73ba8 )
by Reza
03:36
created

StubParser::parseFields()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 4
eloc 7
c 2
b 0
f 1
nc 6
nop 1
dl 0
loc 14
rs 10
1
<?php
2
3
namespace EasyPanel\Parsers;
4
5
use EasyPanel\Parsers\HTMLInputs\BaseInput;
6
use Illuminate\Support\Facades\File;
7
use Illuminate\Support\Str;
8
9
class StubParser
10
{
11
12
    public $texts = [];
13
    private $inputName;
14
    private $parsedModel;
15
16
    public function __construct($inputName, $parsedModel)
17
    {
18
        $this->inputName = $inputName;
19
        $this->parsedModel = $parsedModel;
20
    }
21
22
    public function replaceModel($stub)
23
    {
24
        $fields = $this->getConfig('fields');
25
26
        $modelNamespace = $this->parsedModel;
27
        $modelName = $this->getModelName($modelNamespace);
28
29
        $array = [
30
            '{{ modelName }}' => $modelName,
31
            '{{ modelNamespace }}' => $modelNamespace,
32
            '{{ uploadFile }}' => $this->uploadCodeParser($fields),
33
            '{{ model }}' => strtolower($modelName),
34
            '{{ properties }}' => $this->parseProperties($fields),
35
            '{{ rules }}' => $this->parseValidationRules(),
36
            '{{ fields }}' => $this->parseFields($fields),
37
            '{{ setProperties }}' => $this->parsePropertiesValue($fields),
38
        ];
39
40
        return str_replace(array_keys($array), array_values($array), $stub);
41
    }
42
43
    public function setLocaleTexts()
44
    {
45
        $this->texts[ucfirst($this->inputName)] = ucfirst($this->inputName);
46
        $this->texts[ucfirst(Str::plural($this->inputName))] = ucfirst(Str::plural($this->inputName));
47
        $files = File::glob(resource_path('lang').'/*_panel.json');
48
49
        foreach ($files as $file) {
50
            $decodedFile = json_decode(File::get($file), 1);
51
            $texts = $this->texts;
52
            foreach ($texts as $key => $text) {
53
                if (array_key_exists($key, $decodedFile)){
54
                    unset($texts[$text]);
55
                }
56
            }
57
            $array = array_merge($decodedFile, $texts);
58
            File::put($file, json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
59
        }
60
    }
61
62
    public function parseBlade($stub){
63
        $modelName = $this->getModelName($this->parsedModel);
64
65
        $array = [
66
            '{{ model }}' => strtolower($modelName),
67
            '{{ modelName }}' => $modelName,
68
            '{{ data }}' => $this->parseDataInBlade($modelName),
69
            '{{ titles }}' => $this->parseTitlesInBlade(),
70
            '{{ inputs }}' => $this->parseInputsInBlade(),
71
        ];
72
73
        $this->setLocaleTexts();
74
75
        return str_replace(array_keys($array), array_values($array), $stub);
76
    }
77
78
    public function getConfig($key, $action = null){
79
        $action = $action ?? $this->inputName;
80
81
        return config("easy_panel.crud.$action.$key") ?: [];
82
    }
83
84
    public function getModelName($modelNamespace)
85
    {
86
        $array = explode('\\', $modelNamespace);
87
88
        return end($array);
89
    }
90
91
    public function parseProperties($fields)
92
    {
93
        $fields = array_keys($fields);
94
        $str = '';
95
96
        if(in_array($this->inputName, $fields)){
97
            $this->error("Model name must not equal to column names, fix it and rerun command with -f flag");
0 ignored issues
show
Bug introduced by
The method error() does not exist on EasyPanel\Parsers\StubParser. ( Ignorable by Annotation )

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

97
            $this->/** @scrutinizer ignore-call */ 
98
                   error("Model name must not equal to column names, fix it and rerun command with -f flag");

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
98
            die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
99
        }
100
101
        foreach ($fields as $field) {
102
            $str .= 'public $'.$field.";".$this->makeTab(1);
103
        }
104
105
        return $str;
106
    }
107
108
    public function uploadCodeParser($fields)
109
    {
110
        $filesInput = array_keys($fields, 'file');
111
        $str = '';
112
        foreach ($filesInput as $file) {
113
            // We get store path which has been defined in crud's config file
114
            $storePath = $this->getConfig('store')[$file] ?? "{$file}";
115
116
            // We get property value then store file in $storePath
117
            // A PHP Code for upload as a string will be created here
118
            $str .= $this->makeTab(2).'if($this->getPropertyValue(\''.$file.'\') and is_object($this->'.$file.')) {'.$this->makeTab(3);
119
            $str .= '$this->'.$file.' = $this->getPropertyValue(\''.$file.'\')->store(\''.$storePath.'\');'.$this->makeTab(2);
120
            $str .= '}'.PHP_EOL;
121
        }
122
123
        return $str;
124
    }
125
126
    public function parsePropertiesValue($fields)
127
    {
128
        $fields = array_keys($fields);
129
        $str = '';
130
        $action = $this->inputName;
131
        foreach ($fields as $field) {
132
            $str .= '$this->'.$field.' = $this->'.$action.'->'.$field.';'.$this->makeTab(2, end($fields) != $field);
133
        }
134
135
        return $str;
136
    }
137
138
    public function parseValidationRules()
139
    {
140
        $rules = $this->getConfig('validation');
141
142
        $str = '';
143
        foreach ($rules as $key => $rule) {
144
            $str .= "'$key' => '$rule',".$this->makeTab(2, $rule != end($rules));
145
        }
146
147
        return $str;
148
    }
149
150
    public function parseFields($fields)
151
    {
152
        $str = '';
153
154
        foreach ($fields as $key => $field) {
155
            $newLine = ($field != end($fields) or $this->getConfig('with_auth'));
156
            $str .=  "'$key' => " . '$this' . "->$key,".$this->makeTab(3, $newLine);
157
        }
158
159
        if($this->getConfig('with_auth')){
160
            $str .= "'user_id' => auth()->id(),";
161
        }
162
163
        return $str;
164
    }
165
166
    public function parseDataInBlade($modelName)
167
    {
168
        $fields = $this->getConfig('show');
169
        $str = '';
170
        $modelName = strtolower($modelName);
171
        foreach ($fields as $value) {
172
            if (!is_array($value)) {
173
                if(!in_array($value, ['image', 'photo', 'profile', 'banner'])) {
174
                    $str .= '<td> {{ $' . $modelName . '->' . $value . " }} </td>" . $this->makeTab(1, end($fields) != $value);
175
                } else {
176
                    $str .= '<td><a target="_blank" href="{{ asset($' . $modelName . '->' . $value . ') }}"><img class="rounded-circle img-fluid" width="50" height="50" src="{{ asset($' . $modelName . '->' . $value . ') }}" alt="'.$value.'"></a></td>' . $this->makeTab(1, end($fields) != $value);
177
                }
178
           } else {
179
                $relationName = array_key_first($value);
180
                $str .= '<td> {{ $' . $modelName . '->' . $relationName . '->'. $value[array_key_first($value)] .' }} </td>' . $this->makeTab(1, end($fields) != $value);
181
            }
182
        }
183
184
        return $str;
185
    }
186
187
    public function parseTitlesInBlade()
188
    {
189
        $fields = $this->getConfig('show');
190
        $str = '';
191
        foreach ($fields as $field) {
192
            if (!is_array($field)) {
193
                $sortName = $field;
194
                $field = ucfirst($field);
195
                $str .= "<td style='cursor: pointer' wire:click=\"sort('$sortName')\"> <i class='fa @if(".'$sortType'." == 'desc' and ".'$sortColumn'." == '$sortName') fa-sort-amount-down ml-2 @elseif(".'$sortType == '."'asc' and ".'$sortColumn'." == '$sortName') fa-sort-amount-up ml-2 @endif'></i> {{ __('$field') }} </td>".$this->makeTab(6, end($fields) != $field);
196
            } else {
197
                $relationName = array_key_first($field);
198
                $field = ucfirst($relationName). ' ' . ucfirst($field[array_key_first($field)]);
199
                $str .= "<td> {{ __('$field') }} </td>".$this->makeTab(6, end($fields) != $field);
200
            }
201
            $this->texts[$field] = $field;
202
        }
203
204
        return $str;
205
    }
206
207
    public function parseInputsInBlade()
208
    {
209
        $fields = $this->getConfig('fields');
210
211
        $str = '';
212
        foreach ($fields as $name => $type) {
213
            $title = ucfirst($name);
214
            $this->texts[$title] = ucfirst($name);
215
            $str .= (new BaseInput($name, $type))->render();
216
        }
217
218
        return $str;
219
    }
220
221
    public function makeTab($count, $newLine = true){
222
        $count = $count * 4;
223
        $tabs = str_repeat(' ', $count);
224
225
        return $newLine ? "\n".$tabs : $tabs;
226
    }
227
228
}
229