Completed
Push — master ( 8b9728...8dad3b )
by Michael
10s
created

XoopspollRenderer::assignForm()   B

Complexity

Conditions 9
Paths 64

Size

Total Lines 55
Code Lines 32

Duplication

Lines 7
Ratio 12.73 %

Importance

Changes 0
Metric Value
cc 9
eloc 32
nc 64
nop 1
dl 7
loc 55
rs 7.2446
c 0
b 0
f 0

How to fix   Long Method   

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

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
               XOOPS - PHP Content Management System
4
                   Copyright (c) 2000-2016 XOOPS.org
5
                      <http://xoops.org/>
6
 This program is free software; you can redistribute it and/or modify
7
 it under the terms of the GNU General Public License as published by
8
 the Free Software Foundation; either version 2 of the License, or
9
 (at your option) any later version.
10
11
 You may not change or alter any portion of this comment or credits
12
 of supporting developers from this source code or any supporting
13
 source code which is considered copyrighted (c) material of the
14
 original comment or credit authors.
15
16
 This program is distributed in the hope that it will be useful,
17
 but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 GNU General Public License for more details.
20
21
 You should have received a copy of the GNU General Public License
22
 along with this program; if not, write to the Free Software
23
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
24
*/
25
26
/**
27
 * Poll Renderer class for the XoopsPoll Module
28
 *
29
 * @copyright ::  {@link http://xoops.org/ XOOPS Project}
30
 * @license   ::  {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
31
 * @package   ::  xoopspoll
32
 * @subpackage::  admin
33
 * @since     ::  1.0
34
 * @author    ::  {@link http://www.myweb.ne.jp/ Kazumi Ono (AKA onokazu)}
35
 */
36
37
xoops_loadLanguage('main', 'xoopspoll');
38
xoops_load('constants', 'xoopspoll');
39
xoops_load('pollUtility', 'xoopspoll');
40
41
/**
42
 * Class XoopspollRenderer
43
 */
44
class XoopspollRenderer
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
45
{
46
    // XoopsPoll class object
47
    protected $pollObj;
48
    protected $pHandler;
49
    protected $oHandler;
50
    protected $lHandler;
51
52
    // constructor(s)
53
    /**
54
     * @param null $poll
55
     */
56
    public function __construct($poll = null)
57
    {
58
        // setup handlers
59
        $this->pHandler = xoops_getModuleHandler('poll', 'xoopspoll');
60
        $this->oHandler = xoops_getModuleHandler('option', 'xoopspoll');
61
        $this->lHandler = xoops_getModuleHandler('log', 'xoopspoll');
62
63
        if ($poll instanceof XoopspollPoll) {
64
            $this->pollObj = $poll;
65
        } elseif (!empty($poll) && ((int)$poll > 0)) {
66
            $this->pollObj = $this->pHandler->get((int)$poll);
67
        } else {
68
            $this->pollObj = $this->pHandler->create();
69
        }
70
    }
71
72
    /**
73
     * @param null $poll
74
     */
75
    public function XoopspollRenderer($poll = null)
76
    {
77
        $this->__construct($poll);
78
    }
79
80
    /**
81
     *
82
     * create html form to display poll
83
     * @access public
84
     * @return string html form for display
85
     */
86
    public function renderForm()
0 ignored issues
show
Coding Style introduced by
renderForm 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...
87
    {
88
        $myTpl = new XoopsTpl();
89
        $this->assignForm($myTpl);  // get the poll information
90
91
        return $myTpl->fetch($GLOBALS['xoops']->path('modules/xoopspoll/templates/xoopspoll_view.tpl'));
92
    }
93
94
    /**
95
     *
96
     * assigns form values to template for display
97
     * @access public
98
     * @var    XoopsTpl $tpl
99
     * @return null
100
     */
101
    public function assignForm(XoopsTpl $tpl)
0 ignored issues
show
Coding Style introduced by
assignForm 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...
102
    {
103
        $myts       = MyTextSanitizer::getInstance();
104
        $optionObjs = $this->oHandler->getAllByPollId($this->pollObj->getVar('poll_id'));
105
106
        if (empty($optionObjs)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
107
            /* there was a problem with missing Options */
108
            //            redirect_header($_SERVER['HTTP_REFERER'], XoopspollConstants::REDIRECT_DELAY_MEDIUM, _MD_XOOPSPOLL_ERROR_OPTIONS_MISSING);
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...
109
        }
110
111 View Code Duplication
        if (XoopspollConstants::MULTIPLE_SELECT_POLL === (int) $this->pollObj->getVar('multiple')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
112
            $optionType = 'checkbox';
113
            $optionName = 'option_id[]';
114
        } else {
115
            $optionType = 'radio';
116
            $optionName = 'option_id';
117
        }
118
        foreach ($optionObjs as $optionObj) {
119
            $options[] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = 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...
120
                'input' => "<input type='{$optionType}' " . "name='{$optionName}' " . "value='" . $optionObj->getVar('option_id') . "' />",
121
                'text'  => $optionObj->getVar('option_text')
122
            );
123
        }
124
        $uid = (isset($GLOBALS['xoopsUser'])
125
                && is_object($GLOBALS['xoopsUser'])) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
126
        if ($this->pollObj->isAllowedToVote()
127
            && (!$this->lHandler->hasVoted($this->pollObj->getVar('poll_id'), xoops_getenv('REMOTE_ADDR'), $uid))
128
        ) {
129
            $can_vote = true;
130
        } else {
131
            $can_vote = false;
132
        }
133
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
134
                $tpl->assign('poll', array(
135
                                       'question'     => $myts->htmlSpecialChars($this->pollObj->getVar('question')),
136
                                       'pollId'       => $this->pollObj->getVar('poll_id'),
137
                                       'viewresults'  => $GLOBALS['xoops']->url("modules/xoopspoll/pollresults.php") . "?poll_id=" . $this->pollObj->getVar('poll_id'),
138
                                       'options'      => $options,
139
                                       'description'  => $myts->displayTarea($myts->undoHtmlSpecialChars($this->pollObj->getVar('description')), 1))
140
                );
141
        */
142
        $tpl->assign(array(
143
                         'poll'         => array(
144
                             'question'    => $myts->htmlSpecialChars($this->pollObj->getVar('question')),
145
                             'pollId'      => $this->pollObj->getVar('poll_id'),
146
                             'viewresults' => $GLOBALS['xoops']->url('modules/xoopspoll/pollresults.php') . '?poll_id=' . $this->pollObj->getVar('poll_id'),
147
                             'options'     => isset($options) ? $options : '',
148
                             'description' => $myts->displayTarea($myts->undoHtmlSpecialChars($this->pollObj->getVar('description')), 1)
149
                         ),
150
                         'can_vote'     => $can_vote,
151
                         'action'       => $GLOBALS['xoops']->url('modules/xoopspoll/index.php'),
152
                         'lang_vote'    => _MD_XOOPSPOLL_VOTE,
153
                         'lang_results' => _MD_XOOPSPOLL_RESULTS
154
                     ));
155
    }
156
157
    /**
158
     *
159
     * display html results to screen (echo)
160
     * @access public
161
     * @return null
162
     */
163
    public function renderResults()
0 ignored issues
show
Coding Style introduced by
renderResults 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...
164
    {
165
        $myTpl = new XoopsTpl();
166
        $this->assignResults($myTpl);  // get the poll information
167
168
        return $myTpl->fetch($GLOBALS['xoops']->path('modules/xoopspoll/templates/xoopspoll_results_renderer.tpl'));
169
    }
170
171
    /**
172
     *
173
     * assigns form results to template
174
     * @access public
175
     * @var    XoopsTpl tpl
176
     * @return null
177
     */
178
    public function assignResults(XoopsTpl $tpl)
0 ignored issues
show
Coding Style introduced by
assignResults 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...
179
    {
180
        $myts             = MyTextSanitizer::getInstance();
181
        $xuEndTimestamp   = xoops_getUserTimestamp($this->pollObj->getVar('end_time'));
182
        $xuEndFormatted   = ucfirst(date(_MEDIUMDATESTRING, $xuEndTimestamp));
183
        $xuStartTimestamp = xoops_getUserTimestamp($this->pollObj->getVar('start_time'));
184
        $xuStartFormatted = ucfirst(date(_MEDIUMDATESTRING, $xuStartTimestamp));
185
186
        //        $lHandler = xoops_getModuleHandler('log', 'xoopspoll');
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
187
        $criteria = new CriteriaCompo();
188
        $criteria->add(new Criteria('poll_id', $this->pollObj->getVar('poll_id'), '='));
189
        $criteria->setSort('option_id');
190
        $optObjsArray = $this->oHandler->getAll($criteria);
191
        $total        = $this->pollObj->getVar('votes');
192
        $i            = 0;
193
        foreach ($optObjsArray as $optObj) {
194
            $optionVars = $optObj->getValues();
195
            $percent    = ($total > 0) ? (100 * $optionVars['option_count'] / $total) : 0;
196
            if ($percent > 0) {
197
                $width                = (int)($percent * 2);
198
                $options[$i]['image'] = "<img src='" . $GLOBALS['xoops']->url("modules/xoopspoll/assets/images/colorbars/{$optionVars['option_color']}'") . " style='height: 14px; width: {$width}px; vertical-align: middle;' alt='" . (int)$percent
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = 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...
199
                                        . "%' />";
200
            } else {
201
                $options[$i]['image'] = '';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = 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...
202
            }
203
204
            /* setup module config handler - required since this is called by newbb too */
205
            /** @var XoopsModuleHandler $moduleHandler */
206
            $moduleHandler = xoops_getHandler('module');
207
            $configHandler = xoops_getHandler('config');
208
            $xp_module      = $moduleHandler->getByDirname('xoopspoll');
209
            $module_id      = $xp_module->getVar('mid');
210
            $xp_config      = $configHandler->getConfigsByCat(0, $module_id);
211
212
            if ($xp_config['disp_vote_nums']) {
213
                $options[$i]['percent'] = sprintf(' %01.1f%% (%d)', $percent, $optionVars['option_count']);
0 ignored issues
show
Bug introduced by
The variable $options 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...
214
            } else {
215
                $options[$i]['percent'] = sprintf(' %01.1f%%', $percent);
216
            }
217
            $options[$i]['text']  = $optionVars['option_text'];
218
            $options[$i]['total'] = $optionVars['option_count'];
219
            $options[$i]['value'] = (int) $percent;
220
            ++$i;
221
            unset($optionVars);
222
        }
223
        $uid = (isset($GLOBALS['xoopsUser'])
224
                && is_object($GLOBALS['xoopsUser'])) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
225
        if (!$this->pollObj->hasExpired() && $this->pollObj->isAllowedToVote()
226
            && !$this->lHandler->hasVoted($this->pollObj->getVar('poll_id'), xoops_getenv('REMOTE_ADDR'), $uid)
227
        ) {
228
            $vote = "<a href='" . $GLOBALS['xoops']->url('modules/xoopspoll/index.php') . '?poll_id=' . $this->pollObj->getVar('poll_id') . "'>" . _MD_XOOPSPOLL_VOTE_NOW . '</a>';
229
        } else {
230
            $vote = null;
231
        }
232
        if ($xp_config['disp_vote_nums']) {
0 ignored issues
show
Bug introduced by
The variable $xp_config 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...
233
            $totalVotes  = sprintf(_MD_XOOPSPOLL_TOTALVOTES, $total);
234
            $totalVoters = sprintf(_MD_XOOPSPOLL_TOTALVOTERS, $this->pollObj->getVar('voters'));
235
        } else {
236
            $totalVotes = $totalVoters = '';
237
        }
238
239
        $tpl->assign('poll', array(
240
            'question'    => $myts->htmlSpecialChars($this->pollObj->getVar('question')),
241
            'end_text'    => $xuEndFormatted,
242
            'start_text'  => $xuStartFormatted,
243
            'totalVotes'  => $totalVotes,
244
            'totalVoters' => $totalVoters,
245
            'vote'        => $vote,
246
            'options'     => $options,
247
            'description' => $this->pollObj->getVar('description') //allow html
248
        ));
249
    }
250
}
251