Passed
Push — master ( df1d09...3d81b9 )
by Reza
03:24
created

StubParser::setStore()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
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
    private $fields;
17
    private $inputs;
18
    private $validationRules;
19
    private $hasAuth;
20
    private $store;
21
22
    public function __construct($inputName, $parsedModel)
23
    {
24
        $this->inputName = $inputName;
25
        $this->parsedModel = $parsedModel;
26
    }
27
28
    public function setValidationRules($rules)
29
    {
30
        $this->validationRules = $rules;
31
    }
32
33
    public function setStore($store)
34
    {
35
        $this->store = $store;
36
    }
37
38
    public function setAuthType(bool $hasAuth){
39
        $this->hasAuth = $hasAuth;
40
    }
41
42
    public function setFields(array $fields){
43
        $this->fields = $fields;
44
    }
45
46
    public function setInputs(array $inputs){
47
        $this->inputs = $inputs;
48
    }
49
50
    public function replaceModel($stub)
51
    {
52
        $fields = $this->inputs;
0 ignored issues
show
Unused Code introduced by
The assignment to $fields is dead and can be removed.
Loading history...
53
54
        $modelNamespace = $this->parsedModel;
55
        $modelName = $this->getModelName($modelNamespace);
56
57
        $array = [
58
            '{{ modelName }}' => $modelName,
59
            '{{ modelNamespace }}' => $modelNamespace,
60
            '{{ uploadFile }}' => $this->uploadCodeParser(),
61
            '{{ model }}' => strtolower($modelName),
62
            '{{ properties }}' => $this->parseProperties(),
63
            '{{ rules }}' => $this->parseValidationRules(),
64
            '{{ fields }}' => $this->parseActionInComponent(),
65
            '{{ setProperties }}' => $this->parseSetPropertiesValue(),
66
        ];
67
68
        return str_replace(array_keys($array), array_values($array), $stub);
69
    }
70
71
    /**
72
     * Make Locale files
73
     */
74
    public function setLocaleTexts()
75
    {
76
        $this->texts[ucfirst($this->inputName)] = ucfirst($this->inputName);
77
        $this->texts[ucfirst(Str::plural($this->inputName))] = ucfirst(Str::plural($this->inputName));
78
        $files = File::glob(resource_path('lang').'/*_panel.json');
79
80
        foreach ($files as $file) {
81
            $decodedFile = json_decode(File::get($file), 1);
82
            $texts = $this->texts;
83
            foreach ($texts as $key => $text) {
84
                if (array_key_exists($key, $decodedFile)){
85
                    unset($texts[$text]);
86
                }
87
            }
88
            $array = array_merge($decodedFile, $texts);
89
            File::put($file, json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
90
        }
91
    }
92
93
    /**
94
     * Get model name from namespace
95
     */
96
    public function getModelName($modelNamespace)
97
    {
98
        $array = explode('\\', $modelNamespace);
99
100
        return end($array);
101
    }
102
103
    /**
104
     * Parse properties in Livewire component
105
     */
106
    public function parseProperties()
107
    {
108
        $fields = array_keys($this->inputs);
109
        $str = '';
110
111
        if(in_array($this->inputName, $fields)){
112
            $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

112
            $this->/** @scrutinizer ignore-call */ 
113
                   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...
113
            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...
114
        }
115
116
        foreach ($fields as $field) {
117
            $str .= 'public $'.$field.";".$this->makeTab(1);
118
        }
119
120
        return $str;
121
    }
122
123
    /**
124
     * Parse Uploading Code
125
     */
126
    public function uploadCodeParser()
127
    {
128
        $filesInput = array_keys($this->inputs, 'file');
129
        $str = '';
130
        foreach ($filesInput as $file) {
131
            // We get store path which has been defined in crud's config file
132
            $storePath = $this->store[$file] ?? "{$file}";
133
134
            // We get property value then store file in $storePath
135
            // A PHP Code for upload as a string will be created here
136
            $str .= $this->makeTab(2).'if($this->getPropertyValue(\''.$file.'\') and is_object($this->'.$file.')) {'.$this->makeTab(3);
137
            $str .= '$this->'.$file.' = $this->getPropertyValue(\''.$file.'\')->store(\''.$storePath.'\');'.$this->makeTab(2);
138
            $str .= '}'.PHP_EOL;
139
        }
140
141
        return $str;
142
    }
143
144
    /**
145
     * parse values for mount method in Livewire
146
     */
147
    public function parseSetPropertiesValue()
148
    {
149
        $fields = array_keys($this->inputs);
150
        $str = '';
151
        $action = $this->inputName;
152
        foreach ($fields as $field) {
153
            $str .= '$this->'.$field.' = $this->'.$action.'->'.$field.';'.$this->makeTab(2, end($fields) != $field);
154
        }
155
156
        return $str;
157
    }
158
159
    /**
160
     * Parse Validation rules
161
     */
162
    public function parseValidationRules()
163
    {
164
        $str = '';
165
166
        foreach ($this->validationRules as $key => $rule) {
167
            $str .= "'$key' => '$rule',".$this->makeTab(2, $rule != end($this->validationRules));
168
        }
169
170
        return $str;
171
    }
172
173
    /**
174
     * Create an array of properties in Livewire component for actions
175
     */
176
    public function parseActionInComponent()
177
    {
178
        $str = '';
179
180
        foreach ($this->inputs as $key => $field) {
181
            $newLine = ($field != end($this->inputs) or $this->hasAuth);
182
            $str .=  "'$key' => " . '$this' . "->$key,".$this->makeTab(3, $newLine);
183
        }
184
185
        if($this->hasAuth){
186
            $str .= "'user_id' => auth()->id(),";
187
        }
188
189
        return $str;
190
    }
191
192
    /**
193
     * Create Blade from stub
194
     */
195
    public function parseBlade($stub){
196
        $modelName = $this->getModelName($this->parsedModel);
197
198
        $array = [
199
            '{{ model }}' => strtolower($modelName),
200
            '{{ modelName }}' => $modelName,
201
            '{{ data }}' => $this->parseDataInBlade(),
202
            '{{ titles }}' => $this->parseTitlesInBlade(),
203
            '{{ inputs }}' => $this->parseInputsInBlade(),
204
        ];
205
206
        $this->setLocaleTexts();
207
208
        return str_replace(array_keys($array), array_values($array), $stub);
209
    }
210
211
    /**
212
     * Parse <td> tags for data
213
     */
214
    public function parseDataInBlade()
215
    {
216
        $fields = $this->fields;
217
        $str = '';
218
        $modelName = strtolower($this->getModelName($this->parsedModel));
219
        foreach ($fields as $value) {
220
            if (!is_array($value)) {
221
                if(!in_array($value, ['image', 'photo', 'profile', 'banner'])) {
222
                    $str .= '<td> {{ $' . $modelName . '->' . $value . " }} </td>" . $this->makeTab(1, end($fields) != $value);
223
                } else {
224
                    $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);
225
                }
226
           } else {
227
                $relationName = array_key_first($value);
228
                $str .= '<td> {{ $' . $modelName . '->' . $relationName . '->'. $value[array_key_first($value)] .' }} </td>' . $this->makeTab(1, end($fields) != $value);
229
            }
230
        }
231
232
        return $str;
233
    }
234
235
    /**
236
     * Parse <td> tags for head
237
     */
238
    public function parseTitlesInBlade()
239
    {
240
        $fields = $this->fields;
241
        $str = '';
242
        foreach ($fields as $field) {
243
            if (!is_array($field)) {
244
                $sortName = $field;
245
                $field = ucfirst($field);
246
                $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);
247
            } else {
248
                $relationName = array_key_first($field);
249
                $field = ucfirst($relationName). ' ' . ucfirst($field[array_key_first($field)]);
250
                $str .= "<td> {{ __('$field') }} </td>".$this->makeTab(6, end($fields) != $field);
251
            }
252
            $this->texts[$field] = $field;
253
        }
254
255
        return $str;
256
    }
257
258
    /**
259
     * Create inputs HTML
260
     */
261
    public function parseInputsInBlade()
262
    {
263
        $str = '';
264
        foreach ($this->inputs as $name => $type) {
265
            $title = ucfirst($name);
266
            $this->texts[$title] = ucfirst($name);
267
            $str .= (new BaseInput($name, $type, $this->inputName))->render();
268
        }
269
270
        return $str;
271
    }
272
273
    /**
274
     * Tab Maker (Each tabs mean 4 space)
275
     */
276
    public function makeTab($count, $newLine = true){
277
        $count = $count * 4;
278
        $tabs = str_repeat(' ', $count);
279
280
        return $newLine ? "\n".$tabs : $tabs;
281
    }
282
283
}
284