Completed
Branch master (9dda00)
by Michael
04:54 queued 02:33
created

functions.forum.php ➔ newbbForumSelectBox()   C

Complexity

Conditions 11
Paths 8

Size

Total Lines 54
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 34
nc 8
nop 4
dl 0
loc 54
rs 6.6153
c 0
b 0
f 0

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 15 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * NewBB 5.0x,  the forum module for XOOPS project
4
 *
5
 * @copyright      XOOPS Project (http://xoops.org)
6
 * @license        GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
7
 * @author         Taiwen Jiang (phppp or D.J.) <[email protected]>
8
 * @since          4.00
9
 * @package        module::newbb
10
 */
11
12
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
13
14
defined('NEWBB_FUNCTIONS_INI') || include __DIR__ . '/functions.ini.php';
15
define('NEWBB_FUNCTIONS_FORUM_LOADED', true);
16
17
if (!defined('NEWBB_FUNCTIONS_FORUM')) {
18
    define('NEWBB_FUNCTIONS_FORUM', 1);
19
20
    /**
21
     * @param  null|array   $value             selected forum id
22
     * @param  string $permission        permission (access, all, etc.)
23
     * @param  bool   $categoryDelimiter show delimiter between categories
24
     * @param  bool   $see
25
     * @return string
26
     */
27
    function newbbForumSelectBox($value = null, $permission = 'access', $categoryDelimiter = true, $see = false)
28
    {
29
        global $xoopsUser;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
30
31
        /** @var \NewbbCategoryHandler $categoryHandler */
32
        $categoryHandler = xoops_getModuleHandler('category', 'newbb');
33
        $categories      = $categoryHandler->getByPermission($permission, ['cat_id', 'cat_order', 'cat_title'], false);
34
35
        $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
36
37
        $groups = [XOOPS_GROUP_ANONYMOUS];
38
        if (is_object($xoopsUser)) {
39
            $groups = $xoopsUser->getGroups();
40
        }
41
        sort($groups);
42
        $groupKey = 'forumselect_' . $permission . '_' . md5(implode(',', $groups));
43
        $forums   = $cacheHelper->cacheRead($groupKey, function () use ($categories, $permission) {
44
            /** @var \NewbbCategoryHandler $categoryHandler */
45
            $categoryHandler = xoops_getModuleHandler('category', 'newbb');
46
            $categories      = $categoryHandler->getByPermission($permission, ['cat_id', 'cat_order', 'cat_title'], false);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $categories, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
47
48
            /** @var \NewbbForumHandler $forumHandler */
49
            $forumHandler = xoops_getModuleHandler('forum', 'newbb');
50
            $forums       = $forumHandler->getTree(array_keys($categories), 0, 'all');
51
52
            return $forums;
53
        }, 300);
54
55
        $value = is_array($value) ? $value : [$value];
56
        //$see = is_array($see) ? $see : array($see);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
57
        $box = '';
58
        if (count($forums) > 0) {
59
            foreach (array_keys($categories) as $key) {
60
                if ($categoryDelimiter) {
61
                    $box .= "<option value=0>&nbsp;</option>\n";
62
                }
63
                $box .= "<option value='" . (-1 * $key) . "'>[" . $categories[$key]['cat_title'] . "]</option>\n";
64
                if (empty($forums[$key])) {
65
                    continue;
66
                }
67
                foreach ($forums[$key] as $f => $forum) {
68
                    if ($see && in_array($f, $value)) {
69
                        continue;
70
                    }
71
                    $box .= "<option value='{$f}' " . (in_array($f, $value) ? ' selected' : '') . '>' . $forum['prefix'] . $forum['forum_name'] . "</option>\n";
72
                }
73
            }
74
        } else {
75
            $box .= '<option value=0>' . _MD_NEWBB_NOFORUMINDB . "</option>\n";
76
        }
77
        unset($forums, $categories);
78
79
        return $box;
80
    }
81
82
    /**
83
     * @param  int $forum_id
84
     * @return string
85
     */
86
    function newbbMakeJumpbox($forum_id = 0)
87
    {
88
        $box = '<form name="forum_jumpbox" method="get" action="' . XOOPS_URL . '/modules/newbb/viewforum.php" onsubmit="javascript: if (document.forum_jumpbox.forum.value &lt; 1) {return false;}">';
89
        $box .= '<select class="select" name="forum" onchange="if (this.options[this.selectedIndex].value >0) { document.forms.forum_jumpbox.submit();}">';
90
        $box .= '<option value=0>-- ' . _MD_NEWBB_SELFORUM . ' --</option>';
91
        $box .= newbbForumSelectBox($forum_id);
0 ignored issues
show
Documentation introduced by
$forum_id is of type integer, but the function expects a null|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
92
        $box .= "</select> <input type='submit' class='button' value='" . _GO . "' /></form>";
93
        unset($forums, $categories);
94
95
        return $box;
96
    }
97
98
    /**
99
     * Get structured forums
100
     *
101
     * This is a temporary solution
102
     * To be substituted with a new tree handler
103
     *
104
     * @int integer    $pid    parent forum ID
105
     *
106
     * @param  int  $pid
107
     * @param  bool $refresh
108
     * @return array
109
     */
110 View Code Duplication
    function newbbGetSubForum($pid = 0, $refresh = false)
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111
    {
112
        static $list;
113
        if (!isset($list)) {
114
            $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
115
            $list        = $cacheHelper->read('forum_sub');
116
        }
117
118
        if (!is_array($list) || $refresh) {
119
            $list = newbbCreateSubForumList();
120
        }
121
        if ($pid == 0) {
122
            return $list;
123
        } else {
124
            return @$list[$pid];
125
        }
126
    }
127
128
    /**
129
     * @return array
130
     */
131
    function newbbCreateSubForumList()
0 ignored issues
show
Coding Style introduced by
newbbCreateSubForumList uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
132
    {
133
        /** @var \NewbbForumHandler $forumHandler */
134
        $forumHandler = xoops_getModuleHandler('forum', 'newbb');
135
        $criteria     = new CriteriaCompo(null, 1);
136
        $criteria->setSort('cat_id ASC, parent_forum ASC, forum_order');
137
        $criteria->setOrder('ASC');
138
        $forumsObject = $forumHandler->getObjects($criteria);
139
        require_once $GLOBALS['xoops']->path('modules/newbb/class/tree.php');
140
        $tree        = new NewbbObjectTree($forumsObject, 'forum_id', 'parent_forum');
141
        $forum_array = [];
142
        foreach (array_keys($forumsObject) as $key) {
143
            if (!$child = array_keys($tree->getAllChild($forumsObject[$key]->getVar('forum_id')))) {
144
                continue;
145
            }
146
            $forum_array[$forumsObject[$key]->getVar('forum_id')] = $child;
147
        }
148
        unset($forumsObject, $tree, $criteria);
149
150
        $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
151
        $cacheHelper->write('forum_sub', $forum_array);
152
153
        return $forum_array;
154
    }
155
156
    /**
157
     * @param  int  $forum_id
158
     * @param  bool $refresh
159
     * @return array|mixed|null
160
     */
161 View Code Duplication
    function newbbGetParentForum($forum_id = 0, $refresh = false)
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163
        static $list = null;
164
165
        if (!isset($list)) {
166
            $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
167
            $list        = $cacheHelper->read('forum_parent');
168
        }
169
        if (!is_array($list) || $refresh) {
170
            $list = newbbCreateParentForumList();
171
        }
172
        if ($forum_id == 0) {
173
            return $list;
174
        } else {
175
            return @$list[$forum_id];
176
        }
177
    }
178
179
    /**
180
     * @return array
181
     */
182
    function newbbCreateParentForumList()
0 ignored issues
show
Coding Style introduced by
newbbCreateParentForumList uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
183
    {
184
        /** @var \NewbbForumHandler $forumHandler */
185
        $forumHandler = xoops_getModuleHandler('forum', 'newbb');
186
        $criteria     = new Criteria('1', 1);
187
        $criteria->setSort('parent_forum');
188
        $criteria->setOrder('ASC');
189
        $forumsObject = $forumHandler->getObjects($criteria);
190
        require_once $GLOBALS['xoops']->path('modules/newbb/class/tree.php');
191
        $tree        = new NewbbObjectTree($forumsObject, 'forum_id', 'parent_forum');
192
        $forum_array = [];
193
        foreach (array_keys($forumsObject) as $key) {
194
            $parent_forum = $forumsObject[$key]->getVar('parent_forum');
195
            if (!$parent_forum) {
196
                continue;
197
            }
198
            if (isset($forum_array[$parent_forum])) {
199
                $forum_array[$forumsObject[$key]->getVar('forum_id')]   = $forum_array[$parent_forum];
200
                $forum_array[$forumsObject[$key]->getVar('forum_id')][] = $parent_forum;
201
            } else {
202
                $forum_array[$forumsObject[$key]->getVar('forum_id')] = $tree->getParentForums($forumsObject[$key]->getVar('forum_id'));
203
            }
204
        }
205
        unset($forumsObject, $tree, $criteria);
206
207
        $cacheHelper = new \Xmf\Module\Helper\Cache('newbb');
208
        $cacheHelper->write('forum_parent', $forum_array);
209
210
        return $forum_array;
211
    }
212
}
213