newbb_search()   F
last analyzed

Complexity

Conditions 26
Paths 18432

Size

Total Lines 115
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
eloc 74
nc 18432
nop 9
dl 0
loc 115
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php declare(strict_types=1);
2
3
/**
4
 * NewBB,  the forum module for XOOPS project
5
 *
6
 * @copyright      XOOPS Project (https://xoops.org)
7
 * @license        GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
8
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>, irmtfan <[email protected]>
9
 * @since          4.3
10
 */
11
12
use XoopsModules\Newbb\{
13
    Helper,
14
    ForumHandler,
15
    Post,
16
    PostHandler
17
};
18
19
/** @var Helper $helper */
20
/** @var ForumHandler $forumHandler */
21
/** @var PostHandler $postHandler */
22
/** @var Post $post */
23
24
// completely rewrite by irmtfan - remove hardcode database access, solve order issues, add post_text & topic_id, add highlight and reduce queries
25
26
require_once $GLOBALS['xoops']->path('modules/newbb/include/functions.ini.php');
27
28
/**
29
 * @param array               $queryarray
30
 * @param string              $andor
31
 * @param int                 $limit
32
 * @param int                 $offset
33
 * @param int                 $userid
34
 * @param int|string|mixed[]  $forums
35
 * @param int|string          $sortby
36
 * @param string              $searchin
37
 * @param \CriteriaCompo|null $criteriaExtra
38
 *
39
 * @return (mixed|string)[][]
40
 *
41
 * @psalm-return array<0|positive-int, array{topic_id: mixed, link: string, title: mixed, time: mixed, forum_name: string, forum_link: string, post_text: mixed, uid: mixed, poster: mixed|string}>
42
 */
43
function newbb_search(
44
    array $queryarray,
45
    string $andor,
46
    int $limit,
47
    int $offset,
48
    int $userid,
49
    $forums = 0,
50
    $sortby = 0,
51
    string $searchin = 'both',
52
    \CriteriaCompo $criteriaExtra = null
53
): array {
54
    $criteriaPermissions = null;
55
    global $myts, $xoopsDB;
56
    // irmtfan - in XOOPSCORE/search.php $GLOBALS['xoopsModuleConfig'] is not set
57
    if (!isset($GLOBALS['xoopsModuleConfig'])) {
58
        $GLOBALS['xoopsModuleConfig'] = newbbLoadConfig();
59
    }
60
    // irmtfan - in XOOPSCORE/search.php $xoopsModule is not set
61
    if (!is_object($GLOBALS['xoopsModule']) && is_object($GLOBALS['module'])
62
        && 'newbb' === $GLOBALS['module']->getVar('dirname')) {
63
        $GLOBALS['xoopsModule'] = $GLOBALS['module'];
64
    }
65
66
    $forumHandler = Helper::getInstance()->getHandler('Forum');
67
    $validForums  = $forumHandler->getIdsByValues($forums); // can we use view permission? $forumHandler->getIdsByValues($forums, "view")
0 ignored issues
show
Bug introduced by
It seems like $forums can also be of type string; however, parameter $values of XoopsModules\Newbb\ForumHandler::getIdsByValues() does only seem to accept XoopsModules\Newbb\text|array|integer, 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

67
    $validForums  = $forumHandler->getIdsByValues(/** @scrutinizer ignore-type */ $forums); // can we use view permission? $forumHandler->getIdsByValues($forums, "view")
Loading history...
68
69
    $criteriaPost = new \CriteriaCompo();
70
    $criteriaPost->add(new \Criteria('p.approved', 1), 'AND'); // only active posts
71
72
    $forum_list = []; // get forum lists just for forum names
73
    if ((is_countable($validForums) ? count($validForums) : 0) > 0) {
74
        $criteriaPermissions = new \CriteriaCompo();
75
        $criteriaPermissions->add(new \Criteria('p.forum_id', '(' . implode(',', $validForums) . ')', 'IN'), 'AND');
76
        $forum_list = $forumHandler->getAll(new \Criteria('forum_id', '(' . implode(', ', $validForums) . ')', 'IN'), ['forum_name'], false);
77
    }
78
79
    if (is_numeric($userid) && 0 !== $userid) {
80
        $criteriaUser = new \CriteriaCompo();
81
        $criteriaUser->add(new \Criteria('p.uid', $userid), 'OR');
82
    } elseif ($userid && is_array($userid)) {
83
        $userid       = array_map('\intval', $userid);
84
        $criteriaUser = new \CriteriaCompo();
85
        $criteriaUser->add(new \Criteria('p.uid', '(' . implode(',', $userid) . ')', 'IN'), 'OR');
86
    }
87
88
    $count = 0;
89
    if (is_array($queryarray)) {
0 ignored issues
show
introduced by
The condition is_array($queryarray) is always true.
Loading history...
90
        $count = count($queryarray);
91
    }
92
    $highlightKey = '';
93
    if ($count > 0) {
94
        $criteriaKeywords = new \CriteriaCompo();
95
        foreach ($queryarray as $queryTerm) {
96
            $termCriteria  = new \CriteriaCompo();
97
            $queryTermLike = '%' . $xoopsDB->escape($queryTerm) . '%';
98
            if ('title' === $searchin || 'both' === $searchin) {
99
                $termCriteria->add(new \Criteria('p.subject', $queryTermLike, 'LIKE'), 'OR');
100
            }
101
            if ('text' === $searchin || 'both' === $searchin) {
102
                $termCriteria->add(new \Criteria('t.post_text', $queryTermLike, 'LIKE'), 'OR');
103
            }
104
            $criteriaKeywords->add($termCriteria, $andor);
105
        }
106
        // add highlight keywords to post links
107
        $highlightKey = '&amp;keywords=' . implode(' ', $queryarray);
108
        $highlightKey = str_replace(' ', '+', $highlightKey);
109
    }
110
    $criteria = new \CriteriaCompo();
111
    $criteria->add($criteriaPost, 'AND');
112
    if (null !== $criteriaPermissions) {
113
        $criteria->add($criteriaPermissions, 'AND');
114
    }
115
    if (isset($criteriaUser)) {
116
        $criteria->add($criteriaUser, 'AND');
117
    }
118
    if (isset($criteriaKeywords)) {
119
        $criteria->add($criteriaKeywords, 'AND');
120
    }
121
    if (isset($criteriaExtra)) {
122
        $criteria->add($criteriaExtra, 'AND');
123
    }
124
    //$criteria->setLimit($limit); // no need for this
125
    //$criteria->setStart($offset); // no need for this
126
127
    if (empty($sortby)) {
128
        $sortby = 'p.post_time';
129
    }
130
    $criteria->setSort($sortby);
131
    $order = 'ASC';
132
    if ('p.post_time' === $sortby) {
133
        $order = 'DESC';
134
    }
135
    $criteria->setOrder($order);
136
137
    $postHandler = Helper::getInstance()->getHandler('Post');
138
    $posts       = $postHandler->getPostsByLimit($criteria, $limit, $offset);
139
140
    $ret = [];
141
    $i   = 0;
142
    foreach (array_keys($posts) as $id) {
143
        $post                  = $posts[$id];
144
        $post_data             = $post->getPostBody();
145
        $ret[$i]['topic_id']   = $post->getVar('topic_id');
146
        $ret[$i]['link']       = XOOPS_URL . '/modules/newbb/viewtopic.php?post_id=' . $post->getVar('post_id') . $highlightKey; // add highlight key
147
        $ret[$i]['title']      = $post_data['subject'];
148
        $ret[$i]['time']       = $post_data['date'];
149
        $ret[$i]['forum_name'] = htmlspecialchars((string)$forum_list[$post->getVar('forum_id')]['forum_name'], ENT_QUOTES | ENT_HTML5);
150
        $ret[$i]['forum_link'] = XOOPS_URL . '/modules/newbb/viewforum.php?forum=' . $post->getVar('forum_id');
151
        $ret[$i]['post_text']  = $post_data['text'];
152
        $ret[$i]['uid']        = $post->getVar('uid');
153
        $ret[$i]['poster']     = $post->getVar('uid') ? '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $ret[$i]['uid'] . '">' . $post_data['author'] . '</a>' : $post_data['author'];
154
        ++$i;
155
    }
156
157
    return $ret;
158
}
159