Completed
Push — master ( 53ea58...16270d )
by Michael
04:51
created

search.inc.php ➔ publisher_search()   D

Complexity

Conditions 14
Paths 264

Size

Total Lines 59
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 14
eloc 45
c 4
b 0
f 0
nc 264
nop 9
dl 0
loc 59
rs 4.7027

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
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 36 and the first side effect is on line 21.

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
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
/**
12
 * @copyright       The XUUPS Project http://sourceforge.net/projects/xuups/
13
 * @license         http://www.fsf.org/copyleft/gpl.html GNU public license
14
 * @package         Publisher
15
 * @subpackage      Include
16
 * @since           1.0
17
 * @author          trabis <[email protected]>
18
 */
19
// 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...
20
21
include_once dirname(__DIR__) . '/include/common.php';
22
23
/**
24
 * @param        $queryarray
25
 * @param        $andor
26
 * @param        $limit
27
 * @param        $offset
28
 * @param        $userid
29
 * @param array  $categories
30
 * @param int    $sortby
31
 * @param string $searchin
32
 * @param string $extra
33
 *
34
 * @return array
35
 */
36
function publisher_search($queryarray, $andor, $limit, $offset, $userid, $categories = array(), $sortby = 0, $searchin = '', $extra = '')
37
{
38
    $publisher = PublisherPublisher::getInstance();
39
    $ret       = array();
40
    if ($queryarray == '' || count($queryarray) == 0) {
41
        $hightlightKey = '';
42
    } else {
43
        $keywords      = implode('+', $queryarray);
44
        $hightlightKey = '&amp;keywords=' . $keywords;
45
    }
46
    $itemsObjs        = $publisher->getHandler('item')->getItemsFromSearch($queryarray, $andor, $limit, $offset, $userid, $categories, $sortby, $searchin, $extra);
47
    $withCategoryPath = $publisher->getConfig('search_cat_path');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $withCategoryPath is correct as $publisher->getConfig('search_cat_path') (which targets PublisherPublisher::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
48
    //xoops_load("xoopslocal");
49
    $usersIds = array();
50
    foreach ($itemsObjs as $obj) {
51
        $item['image'] = 'assets/images/item_icon.gif';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$item was never initialized. Although not strictly required by PHP, it is generally a good practice to add $item = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
52
        $item['link']  = $obj->getItemUrl();
0 ignored issues
show
Bug introduced by
The variable $item does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
53
        $item['link'] .= (!empty($hightlightKey) && (strpos($item['link'], '.php?') === false)) ? '?' . ltrim($hightlightKey, '&amp;') : $hightlightKey;
54
        if ($withCategoryPath) {
55
            $item['title'] = $obj->getCategoryPath(false) . ' > ' . $obj->getTitle();
56
        } else {
57
            $item['title'] = $obj->getTitle();
58
        }
59
        $item['time'] = $obj->getVar('datesub'); //must go has unix timestamp
60
        $item['uid']  = $obj->uid();
61
        //"Fulltext search/highlight
62
        $text          = $obj->getBody();
63
        $sanitizedText = '';
64
        $textLower     = strtolower($text);
65
        $queryarray    = is_array($queryarray) ? $queryarray : array($queryarray);
66
67
        if ($queryarray[0] != '' && count($queryarray) > 0) {
68
            foreach ($queryarray as $query) {
69
                $pos     = strpos($textLower, strtolower($query)); //xoops_local("strpos", $textLower, strtolower($query));
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
70
                $start   = max($pos - 100, 0);
71
                $length  = strlen($query) + 200; //xoops_local("strlen", $query) + 200;
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
72
                $context = $obj->highlight(xoops_substr($text, $start, $length, ' [...]'), $query);
73
                $sanitizedText .= '<p>[...] ' . $context . '</p>';
74
            }
75
        }
76
        //End of highlight
77
        $item['text']          = $sanitizedText;
78
        $item['author']        = $obj->author_alias();
79
        $item['datesub']       = $obj->getDatesub($publisher->getConfig('format_date'));
80
        $usersIds[$obj->uid()] = $obj->uid();
81
        $ret[]                 = $item;
82
        unset($item, $sanitizedText);
83
    }
84
    xoops_load('XoopsUserUtility');
85
    $usersNames = XoopsUserUtility::getUnameFromIds($usersIds, $publisher->getConfig('format_realname'), true);
86
    foreach ($ret as $key => $item) {
87
        if ($item['author'] == '') {
88
            $ret[$key]['author'] = isset($usersNames[$item['uid']]) ? $usersNames[$item['uid']] : '';
89
        }
90
    }
91
    unset($usersNames, $usersIds);
92
93
    return $ret;
94
}
95