FieldHandler::insert()   F
last analyzed

Complexity

Conditions 42
Paths 14961

Size

Total Lines 115
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 95
dl 0
loc 115
rs 0
c 0
b 0
f 0
cc 42
nc 14961
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\Suico;
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
/**
26
 * @package             kernel
27
 * @copyright       (c) 2000-2016 XOOPS Project (www.xoops.org)
28
 */
29
30
use XoopsModules\Suico;
31
32
/**
33
 * Class FieldHandler
34
 * @package XoopsModules\Suico
35
 */
36
class FieldHandler extends \XoopsPersistableObjectHandler
37
{
38
    /**
39
     * @param \XoopsDatabase $db
40
     */
41
    public function __construct(\XoopsDatabase $db)
42
    {
43
        parent::__construct($db, 'suico_profile_field', Field::class, 'field_id', 'field_title');
44
    }
45
46
    /**
47
     * Read field information from cached storage
48
     *
49
     * @param bool $force_update read fields from database and not cached storage
50
     *
51
     * @return array
52
     */
53
    public function loadFields($force_update = false)
54
    {
55
        static $fields = [];
56
        if (!empty($force_update) || 0 == \count($fields)) {
57
            $this->table_link = $this->db->prefix('suico_profile_category');
58
            $criteria         = new \Criteria('o.field_id', 0, '!=');
59
            $criteria->setSort('l.cat_weight ASC, o.field_weight');
60
            $field_objs = &$this->getByLink($criteria, ['o.*'], true, 'cat_id', 'cat_id');
61
            foreach (\array_keys($field_objs) as $i) {
62
                $fields[$field_objs[$i]->getVar('field_name')] = $field_objs[$i];
63
            }
64
        }
65
        return $fields;
66
    }
67
68
    /**
69
     * save a profile field in the database
70
     *
71
     * @param \XoopsObject $obj   reference to the object
72
     * @param bool         $force whether to force the query execution despite security settings
73
     *
74
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
75
     * @internal param bool $checkObject check if the object is dirty and clean the attributes
76
     */
77
    public function insert(\XoopsObject $obj, $force = false)
78
    {
79
        if (!($obj instanceof $this->className)) {
80
            return false;
81
        }
82
        /* @var Suico\ProfileHandler $profileHandler */
83
        $profileHandler = Helper::getInstance()->getHandler('Profile');
84
        $obj->setVar('field_name', \str_replace(' ', '_', $obj->getVar('field_name')));
85
        $obj->cleanVars();
86
        $defaultstring = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $defaultstring is dead and can be removed.
Loading history...
87
        switch ($obj->getVar('field_type')) {
88
            case 'datetime':
89
            case 'date':
90
                $obj->setVar('field_valuetype', \XOBJ_DTYPE_INT);
91
                $obj->setVar('field_maxlength', 10);
92
                break;
93
            case 'longdate':
94
                $obj->setVar('field_valuetype', \XOBJ_DTYPE_MTIME);
95
                break;
96
            case 'yesno':
97
                $obj->setVar('field_valuetype', \XOBJ_DTYPE_INT);
98
                $obj->setVar('field_maxlength', 1);
99
                break;
100
            case 'textbox':
101
                if (\XOBJ_DTYPE_INT != $obj->getVar('field_valuetype')) {
102
                    $obj->setVar('field_valuetype', \XOBJ_DTYPE_TXTBOX);
103
                }
104
                break;
105
            case 'autotext':
106
                if (\XOBJ_DTYPE_INT != $obj->getVar('field_valuetype')) {
107
                    $obj->setVar('field_valuetype', \XOBJ_DTYPE_TXTAREA);
108
                }
109
                break;
110
            case 'group_multi':
111
            case 'select_multi':
112
            case 'checkbox':
113
                $obj->setVar('field_valuetype', \XOBJ_DTYPE_ARRAY);
114
                break;
115
            case 'language':
116
            case 'timezone':
117
            case 'theme':
118
                $obj->setVar('field_valuetype', \XOBJ_DTYPE_TXTBOX);
119
                break;
120
            case 'dhtml':
121
            case 'textarea':
122
                $obj->setVar('field_valuetype', \XOBJ_DTYPE_TXTAREA);
123
                break;
124
        }
125
        if ('' === $obj->getVar('field_valuetype')) {
126
            $obj->setVar('field_valuetype', \XOBJ_DTYPE_TXTBOX);
127
        }
128
        if ((!\in_array($obj->getVar('field_name'), $this->getUserVars())) && isset($_REQUEST['field_required'])) {
129
            if ($obj->isNew()) {
130
                //add column to table
131
                $changetype = 'ADD';
132
            } else {
133
                //update column information
134
                $changetype = 'MODIFY COLUMN';
135
            }
136
            $maxlengthstring = $obj->getVar('field_maxlength') > 0 ? '(' . $obj->getVar('field_maxlength') . ')' : '';
137
            //set type
138
            switch ($obj->getVar('field_valuetype')) {
139
                default:
140
                case \XOBJ_DTYPE_ARRAY:
141
                case \XOBJ_DTYPE_UNICODE_ARRAY:
142
                    $type            = 'mediumtext';
143
                    $maxlengthstring = '';
144
                    break;
145
                case \XOBJ_DTYPE_UNICODE_EMAIL:
146
                case \XOBJ_DTYPE_UNICODE_TXTBOX:
147
                case \XOBJ_DTYPE_UNICODE_URL:
148
                case \XOBJ_DTYPE_EMAIL:
149
                case \XOBJ_DTYPE_TXTBOX:
150
                case \XOBJ_DTYPE_URL:
151
                    $type = 'varchar';
152
                    // varchars must have a maxlength
153
                    if (!$maxlengthstring) {
154
                        //so set it to max if maxlength is not set - or should it fail?
155
                        $maxlengthstring = '(255)';
156
                        $obj->setVar('field_maxlength', 255);
157
                    }
158
                    break;
159
                case \XOBJ_DTYPE_INT:
160
                    $type = 'int';
161
                    break;
162
                case \XOBJ_DTYPE_DECIMAL:
163
                    $type = 'decimal(14,6)';
164
                    break;
165
                case \XOBJ_DTYPE_FLOAT:
166
                    $type = 'float(15,9)';
167
                    break;
168
                case \XOBJ_DTYPE_OTHER:
169
                case \XOBJ_DTYPE_UNICODE_TXTAREA:
170
                case \XOBJ_DTYPE_TXTAREA:
171
                    $type            = 'text';
172
                    $maxlengthstring = '';
173
                    break;
174
                case \XOBJ_DTYPE_MTIME:
175
                    $type            = 'date';
176
                    $maxlengthstring = '';
177
                    break;
178
            }
179
            $sql    = 'ALTER TABLE `' . $profileHandler->table . '` ' . $changetype . ' `' . $obj->cleanVars['field_name'] . '` ' . $type . $maxlengthstring . ' NULL';
180
            $result = $force ? $this->db->queryF($sql) : $this->db->query($sql);
181
            if (!$result) {
182
                $obj->setErrors($this->db->error());
183
                return false;
184
            }
185
        }
186
        //change this to also update the cached field information storage
187
        $obj->setDirty();
188
        if (!parent::insert($obj, $force)) {
189
            return false;
190
        }
191
        return $obj->getVar('field_id');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $obj->getVar('field_id') also could return the type array|string which is incompatible with the documented return type boolean.
Loading history...
192
    }
193
194
    /**
195
     * delete a profile field from the database
196
     *
197
     * @param \XoopsObject $obj reference to the object to delete
198
     * @param bool         $force
199
     * @return bool FALSE if failed.
200
     */
201
    public function delete(\XoopsObject $obj, $force = false)
202
    {
203
        if (!($obj instanceof $this->className)) {
204
            return false;
205
        }
206
        /* @var ProfileHandler $profileHandler */
207
        $profileHandler = Helper::getInstance()->getHandler('Profile');
208
        // remove column from table
209
        $sql = 'ALTER TABLE ' . $profileHandler->table . ' DROP `' . $obj->getVar('field_name', 'n') . '`';
210
        if ($this->db->query($sql)) {
211
            //change this to update the cached field information storage
212
            if (!parent::delete($obj, $force)) {
213
                return false;
214
            }
215
            if ($obj->getVar('field_show') || $obj->getVar('field_edit')) {
216
                $moduleSuico = Helper::getInstance()->getModule();
217
                if (\is_object($moduleSuico)) {
218
                    // Remove group permissions
219
                    /* @var \XoopsGroupPermHandler $grouppermHandler */
220
                    $grouppermHandler = \xoops_getHandler('groupperm');
221
                    $criteria         = new \CriteriaCompo(new \Criteria('gperm_modid', $moduleSuico->getVar('mid')));
0 ignored issues
show
Bug introduced by
It seems like $moduleSuico->getVar('mid') can also be of type array and array; however, parameter $value of Criteria::__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

221
                    $criteria         = new \CriteriaCompo(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ $moduleSuico->getVar('mid')));
Loading history...
222
                    $criteria->add(new \Criteria('gperm_itemid', $obj->getVar('field_id')));
223
                    return $grouppermHandler->deleteAll($criteria);
224
                }
225
            }
226
        }
227
        return false;
228
    }
229
230
    /**
231
     * Get array of standard variable names (user table)
232
     *
233
     * @return array
234
     */
235
    public function getUserVars()
236
    {
237
        return [
238
            'uid',
239
            'uname',
240
            'name',
241
            'email',
242
            'url',
243
            'user_avatar',
244
            'user_regdate',
245
            'user_from',
246
            'user_sig',
247
            'user_viewemail',
248
            'actkey',
249
            'pass',
250
            'posts',
251
            'attachsig',
252
            'rank',
253
            'level',
254
            'theme',
255
            'timezone_offset',
256
            'last_login',
257
            'umode',
258
            'uorder',
259
            'notify_method',
260
            'notify_mode',
261
            'user_occ',
262
            'bio',
263
            'user_intrest',
264
            'user_mailok',
265
        ];
266
    }
267
}
268