Passed
Pull Request — master (#81)
by Michael
02:58
created

NotesHandler   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 311
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 40
eloc 151
c 3
b 0
f 0
dl 0
loc 311
rs 9.2

9 Methods

Rating   Name   Duplication   Size   Complexity  
A get2() 0 17 3
A create() 0 12 2
A delete() 0 22 4
B insert2() 0 68 9
A getNotes() 0 38 5
A deleteAll() 0 14 4
A __construct() 0 12 2
B getObjects() 0 32 7
A getCount() 0 14 4

How to fix   Complexity   

Complex Class

Complex classes like NotesHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use NotesHandler, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Yogurt;
6
7
/*
8
 You may not change or alter any portion of this comment or credits
9
 of supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit authors.
11
 
12
 This program is distributed in the hope that it will be useful,
13
 but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
*/
16
17
/**
18
 * @category        Module
19
 * @package         yogurt
20
 * @copyright       {@link https://xoops.org/ XOOPS Project}
21
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
22
 * @author          Bruno Barthez, Marcello Brandão aka  Suico, Mamba, LioMJ  <https://xoops.org>
23
 */
24
25
use CriteriaElement;
26
use MyTextSanitizer;
27
use XoopsDatabase;
28
use XoopsObject;
29
use XoopsPersistableObjectHandler;
30
31
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
32
require_once XOOPS_ROOT_PATH . '/class/module.textsanitizer.php';
33
34
// -------------------------------------------------------------------------
35
// ------------------Notes user handler class -------------------
36
// -------------------------------------------------------------------------
37
38
/**
39
 * NotesHandler class.
40
 * This class provides simple mecanisme forNotes object
41
 */
42
class NotesHandler extends XoopsPersistableObjectHandler
43
{
44
    public $helper;
45
46
    public $isAdmin;
47
48
    /**
49
     * Constructor
50
     * @param \XoopsDatabase|null              $xoopsDatabase
51
     * @param \XoopsModules\Yogurt\Helper|null $helper
52
     */
53
    public function __construct(
54
        ?XoopsDatabase $xoopsDatabase = null,
55
        $helper = null
56
    ) {
57
        /** @var \XoopsModules\Yogurt\Helper $this ->helper */
58
        if (null === $helper) {
59
            $this->helper = Helper::getInstance();
0 ignored issues
show
Bug introduced by
The property helper does not seem to exist on XoopsModules\Yogurt\Helper.
Loading history...
60
        } else {
61
            $this->helper = $helper;
62
        }
63
        $isAdmin = $this->helper->isUserAdmin();
0 ignored issues
show
Unused Code introduced by
The assignment to $isAdmin is dead and can be removed.
Loading history...
64
        parent::__construct($xoopsDatabase, 'yogurt_notes', Notes::class, 'note_id', 'note_id');
65
    }
66
67
    /**
68
     * create a new Groups
69
     *
70
     * @param bool $isNew flag the new objects as "new"?
71
     * @return \XoopsObject Groups
72
     */
73
    public function create(
74
        $isNew = true
75
    ) {
76
        $obj = parent::create($isNew);
77
        if ($isNew) {
78
            $obj->setNew();
79
        } else {
80
            $obj->unsetNew();
81
        }
82
        $obj->helper = $this->helper;
83
84
        return $obj;
85
    }
86
87
    /**
88
     * retrieve aNotes
89
     *
90
     * @param int  $id of theNotes
91
     * @param null $fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
92
     * @return mixed reference to the {@linkNotes} object, FALSE if failed
93
     */
94
    public function get2(
95
        $id = null,
96
        $fields = null
0 ignored issues
show
Unused Code introduced by
The parameter $fields is not used and could be removed. ( Ignorable by Annotation )

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

96
        /** @scrutinizer ignore-unused */ $fields = null

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
97
    ) {
98
        $sql = 'SELECT * FROM ' . $this->db->prefix('yogurt_notes') . ' WHERE note_id=' . $id;
99
        if (!$result = $this->db->query($sql)) {
100
            return false;
101
        }
102
        $numrows = $this->db->getRowsNum($result);
103
        if (1 === $numrows) {
104
            $yogurt_notes = new Notes();
105
            $yogurt_notes->assignVars($this->db->fetchArray($result));
106
107
            return $yogurt_notes;
108
        }
109
110
        return false;
111
    }
112
113
    /**
114
     * insert a new Notes in the database
115
     *
116
     * @param \XoopsObject $xoopsObject   reference to the {@linkNotes}
117
     *                                    object
118
     * @param bool         $force
119
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
120
     */
121
    public function insert2(
122
        XoopsObject $xoopsObject,
123
        $force = false
124
    ) {
125
        global $xoopsConfig;
126
        if (!$xoopsObject instanceof Notes) {
127
            return false;
128
        }
129
        if (!$xoopsObject->isDirty()) {
130
            return true;
131
        }
132
        if (!$xoopsObject->cleanVars()) {
133
            return false;
134
        }
135
136
        $noteId = $note_from = $note_to = $date_created = $private = '';
137
138
        foreach ($xoopsObject->cleanVars as $k => $v) {
139
            ${$k} = $v;
140
        }
141
        //        $now = 'date_add(now(), interval ' . $xoopsConfig['server_TZ'] . ' hour)';
142
143
        if ($xoopsObject->isNew()) {
144
            // add / modify a Notes
145
            $xoopsObject = new Notes();
146
            $format      = 'INSERT INTO %s (note_id, note_text, note_from, note_to, date_created, private)';
147
            $format      .= 'VALUES (%u, %s, %u, %u, %u,%u)';
148
            $sql         = \sprintf(
149
                $format,
150
                $this->db->prefix('yogurt_notes'),
151
                $noteId,
152
                $this->db->quoteString($note_text),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $note_text does not exist. Did you maybe mean $note_to?
Loading history...
153
                $note_from,
154
                $note_to,
155
                $date_created,
156
                $private
157
            );
158
            $force       = true;
159
        } else {
160
            $format = 'UPDATE %s SET ';
161
            $format .= 'note_id=%u, note_text=%s, note_from=%u, note_to=%u, date_created=%u, private=%u';
162
            $format .= ' WHERE note_id = %u';
163
            $sql    = \sprintf(
164
                $format,
165
                $this->db->prefix('yogurt_notes'),
166
                $noteId,
167
                $this->db->quoteString($note_text),
168
                $note_from,
169
                $note_to,
170
                $date_created,
171
                $private,
172
                $noteId
173
            );
174
        }
175
        if ($force) {
176
            $result = $this->db->queryF($sql);
177
        } else {
178
            $result = $this->db->query($sql);
179
        }
180
        if (!$result) {
181
            return false;
182
        }
183
        if (empty($noteId)) {
0 ignored issues
show
introduced by
The condition empty($noteId) is always true.
Loading history...
184
            $noteId = $this->db->getInsertId();
185
        }
186
        $xoopsObject->assignVar('note_id', $noteId);
187
188
        return true;
189
    }
190
191
    /**
192
     * delete aNotes from the database
193
     *
194
     * @param \XoopsObject $xoopsObject reference to theNotes to delete
195
     * @param bool         $force
196
     * @return bool FALSE if failed.
197
     */
198
    public function delete(
199
        XoopsObject $xoopsObject,
200
        $force = false
201
    ) {
202
        if (!$xoopsObject instanceof Notes) {
203
            return false;
204
        }
205
        $sql = \sprintf(
206
            'DELETE FROM %s WHERE note_id = %u',
207
            $this->db->prefix('yogurt_notes'),
208
            $xoopsObject->getVar('note_id')
0 ignored issues
show
Bug introduced by
It seems like $xoopsObject->getVar('note_id') can also be of type array and array; however, parameter $args of sprintf() 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

208
            /** @scrutinizer ignore-type */ $xoopsObject->getVar('note_id')
Loading history...
209
        );
210
        if ($force) {
211
            $result = $this->db->queryF($sql);
212
        } else {
213
            $result = $this->db->query($sql);
214
        }
215
        if (!$result) {
216
            return false;
217
        }
218
219
        return true;
220
    }
221
222
    /**
223
     * retrieve yogurt_notes from the database
224
     *
225
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link CriteriaElement} conditions to be met
226
     * @param bool                                 $id_as_key       use the UID as key for the array?
227
     * @param bool                                 $as_object
228
     * @return array array of {@linkNotes} objects
229
     */
230
    public function &getObjects(
231
        ?CriteriaElement $criteriaElement = null,
232
        $id_as_key = false,
233
        $as_object = true
234
    ) {
235
        $ret   = [];
236
        $limit = $start = 0;
237
        $sql   = 'SELECT * FROM ' . $this->db->prefix('yogurt_notes');
238
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
239
            $sql .= ' ' . $criteriaElement->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere() does not exist on CriteriaElement. Did you maybe mean render()? ( Ignorable by Annotation )

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

239
            $sql .= ' ' . $criteriaElement->/** @scrutinizer ignore-call */ renderWhere();

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...
240
            if ('' !== $criteriaElement->getSort()) {
241
                $sql .= ' ORDER BY ' . $criteriaElement->getSort() . ' ' . $criteriaElement->getOrder();
242
            }
243
            $limit = $criteriaElement->getLimit();
244
            $start = $criteriaElement->getStart();
245
        }
246
        $result = $this->db->query($sql, $limit, $start);
247
        if (!$result) {
248
            return $ret;
249
        }
250
        while (false !== ($myrow = $this->db->fetchArray($result))) {
251
            $yogurt_notes = new Notes();
252
            $yogurt_notes->assignVars($myrow);
253
            if (!$id_as_key) {
254
                $ret[] = &$yogurt_notes;
255
            } else {
256
                $ret[$myrow['note_id']] = &$yogurt_notes;
257
            }
258
            unset($yogurt_notes);
259
        }
260
261
        return $ret;
262
    }
263
264
    /**
265
     * count yogurt_notes matching a condition
266
     *
267
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link CriteriaElement} to match
268
     * @return int count of yogurt_notes
269
     */
270
    public function getCount(
271
        ?CriteriaElement $criteriaElement = null
272
    ) {
273
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('yogurt_notes');
274
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
275
            $sql .= ' ' . $criteriaElement->renderWhere();
276
        }
277
        $result = $this->db->query($sql);
278
        if (!$result) {
279
            return 0;
280
        }
281
        [$count] = $this->db->fetchRow($result);
282
283
        return (int)$count;
284
    }
285
286
    /**
287
     * delete yogurt_notes matching a set of conditions
288
     *
289
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link CriteriaElement}
290
     * @param bool                                 $force
291
     * @param bool                                 $asObject
292
     * @return bool FALSE if deletion failed
293
     */
294
    public function deleteAll(
295
        ?CriteriaElement $criteriaElement = null,
296
        $force = true,
297
        $asObject = false
298
    ) {
299
        $sql = 'DELETE FROM ' . $this->db->prefix('yogurt_notes');
300
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
301
            $sql .= ' ' . $criteriaElement->renderWhere();
302
        }
303
        if (!$result = $this->db->query($sql)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
304
            return false;
305
        }
306
307
        return true;
308
    }
309
310
    /**
311
     * @param                                      $countNotes
312
     * @param \CriteriaElement|\CriteriaCompo|null $criteria
313
     * @return array
314
     */
315
    public function getNotes(
316
        $countNotes,
0 ignored issues
show
Unused Code introduced by
The parameter $countNotes is not used and could be removed. ( Ignorable by Annotation )

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

316
        /** @scrutinizer ignore-unused */ $countNotes,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
317
        $criteria
318
    ) {
319
        $myts = new MyTextSanitizer();
320
        $ret  = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
321
        $sql  = 'SELECT note_id, uid, uname, user_avatar, note_from, note_text, date_created FROM ' . $this->db->prefix(
322
                'yogurt_notes'
323
            ) . ', ' . $this->db->prefix(
324
                'users'
325
            );
326
        if (isset($criteria) && $criteria instanceof CriteriaElement) {
327
            $sql .= ' ' . $criteria->renderWhere();
328
            //attention here this is kind of a hack
329
            $sql .= ' AND uid = note_from';
330
            if ('' !== $criteria->getSort()) {
331
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
332
            }
333
            $limit = $criteria->getLimit();
334
            $start = $criteria->getStart();
335
336
            $result = $this->db->query($sql, $limit, $start);
337
            $vetor  = [];
338
            $i      = 0;
339
340
            while (false !== ($myrow = $this->db->fetchArray($result))) {
341
                $vetor[$i]['uid']          = $myrow['uid'];
342
                $vetor[$i]['uname']        = $myrow['uname'];
343
                $vetor[$i]['user_avatar']  = $myrow['user_avatar'];
344
                $temptext                  = $myts->xoopsCodeDecode($myrow['note_text'], 1);
345
                $vetor[$i]['text']         = $myts->nl2Br($temptext);
346
                $vetor[$i]['id']           = $myrow['note_id'];
347
                $vetor[$i]['date_created'] = \formatTimestamp($myrow['date_created'], 's');
348
349
                $i++;
350
            }
351
352
            return $vetor;
353
        }
354
    }
355
}
356