Passed
Pull Request — master (#81)
by Michael
03:00
created

Field::getEditElement()   F

Complexity

Conditions 28
Paths 336

Size

Total Lines 115
Code Lines 87

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 87
dl 0
loc 115
rs 1.6333
c 1
b 0
f 0
cc 28
nc 336
nop 2

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
declare(strict_types=1);
4
5
namespace XoopsModules\Yogurt;
6
7
/**
8
 * Extended User Profile
9
 *
10
 * You may not change or alter any portion of this comment or credits
11
 * of supporting developers from this source code or any supporting source code
12
 * which is considered copyrighted (c) material of the original comment or credit authors.
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
 *
17
 * @copyright       (c) 2000-2016 XOOPS Project (www.xoops.org)
18
 * @license             GNU GPL 2 (http://www.gnu.org/licenses/gpl-2.0.html)
19
 * @package             profile
20
 * @since               2.3.0
21
 * @author              Jan Pedersen
22
 * @author              Taiwen Jiang <[email protected]>
23
 */
24
25
// defined('XOOPS_ROOT_PATH') || exit("XOOPS root path not defined");
26
27
/**
28
 * @package             kernel
29
 * @copyright       (c) 2000-2016 XOOPS Project (www.xoops.org)
30
 */
31
class Field extends \XoopsObject
32
{
33
    public function __construct()
34
    {
35
        $this->initVar('field_id', \XOBJ_DTYPE_INT, null);
36
37
        $this->initVar('cat_id', \XOBJ_DTYPE_INT, null, true);
38
39
        $this->initVar('field_type', \XOBJ_DTYPE_TXTBOX);
40
41
        $this->initVar('field_valuetype', \XOBJ_DTYPE_INT, null, true);
42
43
        $this->initVar('field_name', \XOBJ_DTYPE_TXTBOX, null, true);
44
45
        $this->initVar('field_title', \XOBJ_DTYPE_TXTBOX);
46
47
        $this->initVar('field_description', \XOBJ_DTYPE_TXTAREA);
48
49
        $this->initVar('field_required', \XOBJ_DTYPE_INT, 0); //0 = no, 1 = yes
50
51
        $this->initVar('field_maxlength', \XOBJ_DTYPE_INT, 0);
52
53
        $this->initVar('field_weight', \XOBJ_DTYPE_INT, 0);
54
55
        $this->initVar('field_default', \XOBJ_DTYPE_TXTAREA, '');
56
57
        $this->initVar('field_notnull', \XOBJ_DTYPE_INT, 1);
58
59
        $this->initVar('field_edit', \XOBJ_DTYPE_INT, 0);
60
61
        $this->initVar('field_show', \XOBJ_DTYPE_INT, 0);
62
63
        $this->initVar('field_config', \XOBJ_DTYPE_INT, 0);
64
65
        $this->initVar('field_options', \XOBJ_DTYPE_ARRAY, []);
66
67
        $this->initVar('step_id', \XOBJ_DTYPE_INT, 0);
68
    }
69
70
    /**
71
     * Extra treatment dealing with non latin encoding
72
     * Tricky solution
73
     * @param string $key
74
     * @param mixed  $value
75
     * @param bool   $not_gpc
76
     */
77
78
    public function setVar($key, $value, $not_gpc = false)
79
    {
80
        if ('field_options' === $key && \is_array($value)) {
81
            foreach (\array_keys($value) as $idx) {
82
                $value[$idx] = \base64_encode($value[$idx]);
83
            }
84
        }
85
86
        parent::setVar($key, $value, $not_gpc);
87
    }
88
89
    /**
90
     * @param string $key
91
     * @param string $format
92
     *
93
     * @return mixed
94
     */
95
96
    public function getVar($key, $format = 's')
97
    {
98
        $value = parent::getVar($key, $format);
99
100
        if ('field_options' === $key && !empty($value)) {
101
            foreach (\array_keys($value) as $idx) {
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type boolean and string; however, parameter $input of array_keys() does only seem to accept array, 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

101
            foreach (\array_keys(/** @scrutinizer ignore-type */ $value) as $idx) {
Loading history...
102
                $value[$idx] = \base64_decode($value[$idx]);
103
            }
104
        }
105
106
        return $value;
107
    }
108
109
    /**
110
     * Returns a {@link XoopsFormElement} for editing the value of this field
111
     *
112
     * @param XoopsUser      $user    {@link XoopsUser} object to edit the value of
0 ignored issues
show
Bug introduced by
The type XoopsModules\Yogurt\XoopsUser was not found. Did you mean XoopsUser? If so, make sure to prefix the type with \.
Loading history...
113
     * @param ProfileProfile $profile {@link ProfileProfile} object to edit the value of
0 ignored issues
show
Bug introduced by
The type XoopsModules\Yogurt\ProfileProfile was not found. Did you mean ProfileProfile? If so, make sure to prefix the type with \.
Loading history...
114
     *
115
     * @return \XoopsModules\Yogurt\XoopsFormCheckBox|\XoopsModules\Yogurt\XoopsFormDatetime|\XoopsModules\Yogurt\XoopsFormDhtmlTextArea|\XoopsModules\Yogurt\XoopsFormLabel|\XoopsModules\Yogurt\XoopsFormRadio|\XoopsModules\Yogurt\XoopsFormRadioYN|\XoopsModules\Yogurt\XoopsFormSelect|\XoopsModules\Yogurt\XoopsFormSelectGroup|\XoopsModules\Yogurt\XoopsFormSelectLang|\XoopsModules\Yogurt\XoopsFormSelectTheme|\XoopsModules\Yogurt\XoopsFormSelectTimezone|\XoopsModules\Yogurt\XoopsFormText|\XoopsModules\Yogurt\XoopsFormTextArea|\XoopsModules\Yogurt\XoopsFormTextDateSelect
0 ignored issues
show
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormRadioYN was not found. Did you mean XoopsFormRadioYN? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormText was not found. Did you mean XoopsFormText? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormTextArea was not found. Did you mean XoopsFormTextArea? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormDhtmlTextArea was not found. Did you mean XoopsFormDhtmlTextArea? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormTextDateSelect was not found. Did you mean XoopsFormTextDateSelect? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormLabel was not found. Did you mean XoopsFormLabel? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormRadio was not found. Did you mean XoopsFormRadio? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormSelectTheme was not found. Did you mean XoopsFormSelectTheme? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormSelectGroup was not found. Did you mean XoopsFormSelectGroup? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormSelect was not found. Did you mean XoopsFormSelect? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormDatetime was not found. Did you mean XoopsFormDatetime? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormCheckBox was not found. Did you mean XoopsFormCheckBox? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormSelectTimezone was not found. Did you mean XoopsFormSelectTimezone? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The type XoopsModules\Yogurt\XoopsFormSelectLang was not found. Did you mean XoopsFormSelectLang? If so, make sure to prefix the type with \.
Loading history...
116
     */
117
118
    public function getEditElement($user, $profile)
119
    {
120
        $value = \in_array($this->getVar('field_name'), $this->getUserVars()) ? $user->getVar($this->getVar('field_name'), 'e') : $profile->getVar($this->getVar('field_name'), 'e');
121
122
        $caption = $this->getVar('field_title');
123
124
        $caption = \defined($caption) ? \constant($caption) : $caption;
125
126
        $name = $this->getVar('field_name', 'e');
127
128
        $options = $this->getVar('field_options');
129
130
        if (\is_array($options)) {
131
            //asort($options);
132
133
            foreach (\array_keys($options) as $key) {
134
                $optval = \defined($options[$key]) ? \constant($options[$key]) : $options[$key];
135
136
                $optkey = \defined($key) ? \constant($key) : $key;
137
138
                unset($options[$key]);
139
140
                $options[$optkey] = $optval;
141
            }
142
        }
143
144
        include_once $GLOBALS['xoops']->path('class/xoopsformloader.php');
145
146
        switch ($this->getVar('field_type')) {
147
            default:
148
            case 'autotext':
149
                //autotext is not for editing
150
                $element = new \XoopsFormLabel($caption, $this->getOutputValue($user, $profile));
0 ignored issues
show
Bug introduced by
It seems like $this->getOutputValue($user, $profile) can also be of type array and array; however, parameter $value of XoopsFormLabel::__construct() 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

150
                $element = new \XoopsFormLabel($caption, /** @scrutinizer ignore-type */ $this->getOutputValue($user, $profile));
Loading history...
151
                break;
152
            case 'textbox':
153
                $element = new \XoopsFormText($caption, $name, 35, $this->getVar('field_maxlength'), $value);
154
                break;
155
            case 'textarea':
156
                $element = new \XoopsFormTextArea($caption, $name, $value, 4, 30);
157
                break;
158
            case 'dhtml':
159
                $element = new \XoopsFormDhtmlTextArea($caption, $name, $value, 10, 30);
160
                break;
161
            case 'select':
162
                $element = new \XoopsFormSelect($caption, $name, $value);
163
                // If options do not include an empty element, then add a blank option to prevent any default selection
164
                //                if (!in_array('', array_keys($options))) {
165
                if (!\array_key_exists('', $options)) {
166
                    $element->addOption('', \_NONE);
167
168
                    $eltmsg = empty($caption) ? \sprintf(\_FORM_ENTER, $name) : \sprintf(\_FORM_ENTER, $caption);
169
170
                    $eltmsg = \str_replace('"', '\"', \stripslashes($eltmsg));
171
172
                    $element->customValidationCode[] = "\nvar hasSelected = false; var selectBox = myform.{$name};"
173
                                                       . "for (i = 0; i < selectBox.options.length; i++) { if (selectBox.options[i].selected == true && selectBox.options[i].value != '') { hasSelected = true; break; } }"
174
                                                       . "if (!hasSelected) { window.alert(\"{$eltmsg}\"); selectBox.focus(); return false; }";
175
                }
176
                $element->addOptionArray($options);
177
                break;
178
            case 'select_multi':
179
                $element = new \XoopsFormSelect($caption, $name, $value, 5, true);
180
                $element->addOptionArray($options);
181
                break;
182
            case 'radio':
183
                $element = new \XoopsFormRadio($caption, $name, $value);
184
                $element->addOptionArray($options);
185
                break;
186
            case 'checkbox':
187
                $element = new \XoopsFormCheckBox($caption, $name, $value);
188
                $element->addOptionArray($options);
189
                break;
190
            case 'yesno':
191
                $element = new \XoopsFormRadioYN($caption, $name, $value);
192
                break;
193
            case 'group':
194
                $element = new \XoopsFormSelectGroup($caption, $name, true, $value);
195
                break;
196
            case 'group_multi':
197
                $element = new \XoopsFormSelectGroup($caption, $name, true, $value, 5, true);
198
                break;
199
            case 'language':
200
                $element = new \XoopsFormSelectLang($caption, $name, $value);
201
                break;
202
            case 'date':
203
                $element = new \XoopsFormTextDateSelect($caption, $name, 15, $value);
204
                break;
205
            case 'longdate':
206
                $element = new \XoopsFormTextDateSelect($caption, $name, 15, \str_replace('-', '/', $value));
207
                break;
208
            case 'datetime':
209
                $element = new \XoopsFormDatetime($caption, $name, 15, $value);
210
                break;
211
            case 'timezone':
212
                $element = new \XoopsFormSelectTimezone($caption, $name, $value);
213
                $element->setExtra("style='width: 280px;'");
214
                break;
215
            case 'rank':
216
                $element = new \XoopsFormSelect($caption, $name, $value);
217
218
                include_once $GLOBALS['xoops']->path('class/xoopslists.php');
219
                $ranks = \XoopsLists::getUserRankList();
220
                $element->addOption(0, '--------------');
221
                $element->addOptionArray($ranks);
222
                break;
223
            case 'theme':
224
                $element = new \XoopsFormSelectTheme($caption, $name, $value, 1, true);
225
                break;
226
        }
227
228
        if ('' != $this->getVar('field_description')) {
229
            $element->setDescription($this->getVar('field_description'));
230
        }
231
232
        return $element;
233
    }
234
235
    /**
236
     * Returns a value for output of this field
237
     *
238
     * @param XoopsUser      $user    {@link XoopsUser} object to get the value of
239
     * @param profileProfile $profile object to get the value of
0 ignored issues
show
Bug introduced by
The type XoopsModules\Yogurt\profileProfile was not found. Did you mean profileProfile? If so, make sure to prefix the type with \.
Loading history...
240
     *
241
     * @return mixed
242
     **/
243
244
    public function getOutputValue($user, $profile)
245
    {
246
        if (\file_exists($file = $GLOBALS['xoops']->path('modules/yogurt/language/' . $GLOBALS['xoopsConfig']['language'] . '/modinfo.php'))) {
247
            include_once $file;
248
        } else {
249
            include_once $GLOBALS['xoops']->path('modules/yogurt/language/english/modinfo.php');
250
        }
251
252
        $value = \in_array($this->getVar('field_name'), $this->getUserVars()) ? $user->getVar($this->getVar('field_name')) : $profile->getVar($this->getVar('field_name'));
253
254
        switch ($this->getVar('field_type')) {
255
            default:
256
            case 'textbox':
257
                $value = \is_array($value) ? $value[0] : $value;
258
                if ('url' === $this->getVar('field_name') && '' !== $value) {
259
                    return '<a href="' . \formatURL($value) . '" rel="external">' . $value . '</a>';
260
                }
261
262
                return $value;
263
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
264
            case 'textarea':
265
            case 'dhtml':
266
            case 'theme':
267
            case 'language':
268
                return $value;
269
                break;
270
            case 'select':
271
            case 'radio':
272
                $value   = \is_array($value) ? $value[0] : $value;
273
                $options = $this->getVar('field_options');
274
                if (isset($options[$value])) {
275
                    $value = \htmlspecialchars(\defined($options[$value]) ? \constant($options[$value]) : $options[$value]);
276
                } else {
277
                    $value = '';
278
                }
279
280
                return $value;
281
                break;
282
            case 'select_multi':
283
            case 'checkbox':
284
                $options = $this->getVar('field_options');
285
                $ret     = [];
286
                if (\count($options) > 0) {
287
                    foreach (\array_keys($options) as $key) {
288
                        if (\in_array($key, $value)) {
289
                            $ret[$key] = \htmlspecialchars(\defined($options[$key]) ? \constant($options[$key]) : $options[$key]);
290
                        }
291
                    }
292
                }
293
294
                return $ret;
295
                break;
296
            case 'group':
297
                /* @var XoopsMemberHandler $memberHandler */ $memberHandler = \xoops_getHandler('member');
298
                $options                                                      = $memberHandler->getGroupList();
299
                $ret                                                          = $options[$value] ?? '';
300
301
                return $ret;
302
                break;
303
            case 'group_multi':
304
                /* @var XoopsMemberHandler $memberHandler */ $memberHandler = \xoops_getHandler('member');
305
                $options                                                      = $memberHandler->getGroupList();
306
                $ret                                                          = [];
307
                foreach (\array_keys($options) as $key) {
308
                    if (\in_array($key, $value)) {
309
                        $ret[$key] = \htmlspecialchars($options[$key]);
310
                    }
311
                }
312
313
                return $ret;
314
                break;
315
            case 'longdate':
316
                //return YYYY/MM/DD format - not optimal as it is not using local date format, but how do we do that
317
                //when we cannot convert it to a UNIX timestamp?
318
                return \str_replace('-', '/', $value);
319
            case 'date':
320
                return \formatTimestamp($value, 's');
321
                break;
322
            case 'datetime':
323
                if (!empty($value)) {
324
                    return \formatTimestamp($value, 'm');
325
                }
326
327
                return $value = _MI_YOGURT_NEVER_LOGGED_IN;
0 ignored issues
show
Unused Code introduced by
The assignment to $value is dead and can be removed.
Loading history...
328
                break;
329
            case 'autotext':
330
                $value = $user->getVar($this->getVar('field_name'), 'n'); //autotext can have HTML in it
331
                $value = \str_replace('{X_UID}', $user->getVar('uid'), $value);
332
                $value = \str_replace('{X_URL}', XOOPS_URL, $value);
333
                $value = \str_replace('{X_UNAME}', $user->getVar('uname'), $value);
334
335
                return $value;
336
                break;
337
            case 'rank':
338
                $userrank       = $user->rank();
339
                $user_rankimage = '';
340
                if (isset($userrank['image']) && '' !== $userrank['image']) {
341
                    $user_rankimage = '<img src="' . \XOOPS_UPLOAD_URL . '/' . $userrank['image'] . '" alt="' . $userrank['title'] . '" /> ';
342
                }
343
344
                return $user_rankimage . $userrank['title'];
345
                break;
346
            case 'yesno':
347
                return $value ? \_YES : \_NO;
348
                break;
349
            case 'timezone':
350
                include_once $GLOBALS['xoops']->path('class/xoopslists.php');
351
                $timezones = \XoopsLists::getTimeZoneList();
352
                $value     = empty($value) ? '0' : (string)$value;
353
354
                return $timezones[\str_replace('.0', '', $value)];
355
                break;
356
        }
357
    }
358
359
    /**
360
     * Returns a value ready to be saved in the database
361
     *
362
     * @param mixed $value Value to format
363
     *
364
     * @return mixed
365
     */
366
367
    public function getValueForSave($value)
368
    {
369
        switch ($this->getVar('field_type')) {
370
            default:
371
            case 'textbox':
372
            case 'textarea':
373
            case 'dhtml':
374
            case 'yesno':
375
            case 'timezone':
376
            case 'theme':
377
            case 'language':
378
            case 'select':
379
            case 'radio':
380
            case 'select_multi':
381
            case 'group':
382
            case 'group_multi':
383
            case 'longdate':
384
                return $value;
385
            case 'checkbox':
386
                return (array)$value;
387
            case 'date':
388
                if ('' !== $value) {
389
                    return \strtotime($value);
390
                }
391
392
                return $value;
393
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
394
            case 'datetime':
395
                if (!empty($value)) {
396
                    return \strtotime($value['date']) + (int)$value['time'];
397
                }
398
399
                return $value;
400
                break;
401
        }
402
    }
403
404
    /**
405
     * Get names of user variables
406
     *
407
     * @return array
408
     */
409
410
    public function getUserVars()
411
    {
412
        /* @var ProfileProfileHandler $profile_handler */
413
414
        $profile_handler = \xoops_getModuleHandler('profile', 'yogurt');
415
416
        return $profile_handler->getUserVars();
417
    }
418
}
419