Passed
Pull Request — master (#18)
by Michael
04:31
created

Renderer   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 105
c 0
b 0
f 0
dl 0
loc 197
rs 10
wmc 27

6 Methods

Rating   Name   Duplication   Size   Complexity  
A renderResults() 0 6 1
A renderForm() 0 6 1
A __construct() 0 13 4
A Renderer() 0 3 1
C assignResults() 0 69 11
B assignForm() 0 52 9
1
<?php
2
3
namespace XoopsModules\Xoopspoll;
4
5
/*
6
               XOOPS - PHP Content Management System
7
                   Copyright (c) 2000-2020 XOOPS.org
8
                      <https://xoops.org>
9
 This program is free software; you can redistribute it and/or modify
10
 it under the terms of the GNU General Public License as published by
11
 the Free Software Foundation; either version 2 of the License, or
12
 (at your option) any later version.
13
14
 You may not change or alter any portion of this comment or credits
15
 of supporting developers from this source code or any supporting
16
 source code which is considered copyrighted (c) material of the
17
 original comment or credit authors.
18
19
 This program is distributed in the hope that it will be useful,
20
 but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 GNU General Public License for more details.
23
24
 You should have received a copy of the GNU General Public License
25
 along with this program; if not, write to the Free Software
26
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
27
*/
28
29
/**
30
 * Poll Renderer class for the XoopsPoll Module
31
 *
32
 * @copyright ::  {@link https://xoops.org/ XOOPS Project}
33
 * @license   ::  {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
34
 * @package   ::  xoopspoll
35
 * @subpackage::  admin
36
 * @since     ::  1.0
37
 * @author    ::  {@link http://www.myweb.ne.jp/ Kazumi Ono (AKA onokazu)}
38
 */
39
40
use Xmf\Request;
41
use XoopsModules\Xoopspoll;
42
43
\xoops_loadLanguage('main', 'xoopspoll');
44
//xoops_load('constants', 'xoopspoll');
45
//xoops_load('pollUtility', 'xoopspoll');
46
47
/**
48
 * Class Renderer
49
 */
50
class Renderer
51
{
52
    // XoopsPoll class object
53
    protected $pollObj;
54
    protected $pollHandler;
55
    protected $optionHandler;
56
    protected $logHandler;
57
58
    // constructor(s)
59
60
    /**
61
     * @param null $poll
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $poll is correct as it would always require null to be passed?
Loading history...
62
     */
63
    public function __construct($poll = null)
64
    {
65
        // setup handlers
66
        $this->pollHandler   = Xoopspoll\Helper::getInstance()->getHandler('Poll');
67
        $this->optionHandler = Xoopspoll\Helper::getInstance()->getHandler('Option');
68
        $this->logHandler    = Xoopspoll\Helper::getInstance()->getHandler('Log');
69
70
        if ($poll instanceof \Xoopspoll\Poll) {
0 ignored issues
show
Bug introduced by
The type Xoopspoll\Poll was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
71
            $this->pollObj = $poll;
72
        } elseif (!empty($poll) && ((int)$poll > 0)) {
73
            $this->pollObj = $this->pollHandler->get((int)$poll);
74
        } else {
75
            $this->pollObj = $this->pollHandler->create();
76
        }
77
    }
78
79
    /**
80
     * @param null $poll
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $poll is correct as it would always require null to be passed?
Loading history...
81
     */
82
    public function Renderer($poll = null)
83
    {
84
        $this->__construct($poll);
85
    }
86
87
    /**
88
     * create html form to display poll
89
     * @access public
90
     * @return string html form for display
91
     */
92
    public function renderForm()
93
    {
94
        $myTpl = new \XoopsTpl();
95
        $this->assignForm($myTpl);  // get the poll information
96
97
        return $myTpl->fetch($GLOBALS['xoops']->path('modules/xoopspoll/templates/xoopspoll_view.tpl'));
98
    }
99
100
    /**
101
     * assigns form values to template for display
102
     * @access public
103
     * @var    \XoopsTpl $tpl
104
     */
105
    public function assignForm(\XoopsTpl $tpl)
106
    {
107
        $myts       = \MyTextSanitizer::getInstance();
108
        $optionObjs = $this->optionHandler->getAllByPollId($this->pollObj->getVar('poll_id'));
109
110
        if (empty($optionObjs)) {
111
            /* there was a problem with missing Options */
112
            //            redirect_header(Request::getString('HTTP_REFERER', '', 'SERVER'), Constants::REDIRECT_DELAY_MEDIUM, _MD_XOOPSPOLL_ERROR_OPTIONS_MISSING);
113
        }
114
115
        if (Constants::MULTIPLE_SELECT_POLL === $this->pollObj->getVar('multiple')) {
116
            $optionType = 'checkbox';
117
            $optionName = 'option_id[]';
118
        } else {
119
            $optionType = 'radio';
120
            $optionName = 'option_id';
121
        }
122
        foreach ($optionObjs as $optionObj) {
123
            $options[] = [
124
                'input' => "<input type='{$optionType}' " . "name='{$optionName}' " . "value='" . $optionObj->getVar('option_id') . "'>",
125
                'text'  => $optionObj->getVar('option_text'),
126
            ];
127
        }
128
        $uid = (isset($GLOBALS['xoopsUser'])
129
                     && \is_object($GLOBALS['xoopsUser'])) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
130
        $can_vote = false;
131
        if ($this->pollObj->isAllowedToVote()
0 ignored issues
show
Bug introduced by
The method isAllowedToVote() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

131
        if ($this->pollObj->/** @scrutinizer ignore-call */ isAllowedToVote()
Loading history...
132
            && (!$this->logHandler->hasVoted($this->pollObj->getVar('poll_id'), \xoops_getenv('REMOTE_ADDR'), $uid))) {
133
            $can_vote = true;
134
        }
135
        /*
136
                $tpl->assign('poll', array(
137
                                       'question'     => $myts->htmlSpecialChars($this->pollObj->getVar('question')),
138
                                       'pollId'       => $this->pollObj->getVar('poll_id'),
139
                                       'viewresults'  => $GLOBALS['xoops']->url("modules/xoopspoll/pollresults.php") . "?poll_id=" . $this->pollObj->getVar('poll_id'),
140
                                       'options'      => $options,
141
                                       'description'  => $myts->displayTarea($myts->undoHtmlSpecialChars($this->pollObj->getVar('description')), 1))
142
                );
143
        */
144
        $tpl->assign(
145
            [
146
                'poll'         => [
147
                             'question'    => $myts->htmlSpecialChars($this->pollObj->getVar('question')),
148
                             'pollId'      => $this->pollObj->getVar('poll_id'),
149
                             'viewresults' => $GLOBALS['xoops']->url('modules/xoopspoll/pollresults.php') . '?poll_id=' . $this->pollObj->getVar('poll_id'),
150
                             'options'     => isset($options) ? $options : '',
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $options seems to be defined by a foreach iteration on line 122. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
151
                    'description' => $myts->displayTarea($myts->undoHtmlSpecialChars($this->pollObj->getVar('description')), 1),
152
                ],
153
                         'can_vote'     => $can_vote,
154
                         'action'       => $GLOBALS['xoops']->url('modules/xoopspoll/index.php'),
155
                'lang_vote'    => \_MD_XOOPSPOLL_VOTE,
156
                'lang_results' => \_MD_XOOPSPOLL_RESULTS,
157
            ]
158
        );
159
    }
160
161
    /**
162
     * display html results to screen (echo)
163
     * @access public
164
     */
165
    public function renderResults()
166
    {
167
        $myTpl = new \XoopsTpl();
168
        $this->assignResults($myTpl);  // get the poll information
169
170
        return $myTpl->fetch($GLOBALS['xoops']->path('modules/xoopspoll/templates/xoopspoll_results_renderer.tpl'));
171
    }
172
173
    /**
174
     * assigns form results to template
175
     * @access public
176
     * @var    \XoopsTpl tpl
177
     */
178
    public function assignResults(\XoopsTpl $tpl)
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
        //        $logHandler = Xoopspoll\Helper::getInstance()->getHandler('Log');
187
        $criteria = new \CriteriaCompo();
188
        $criteria->add(new \Criteria('poll_id', $this->pollObj->getVar('poll_id'), '='));
0 ignored issues
show
Bug introduced by
It seems like $this->pollObj->getVar('poll_id') can also be of type array and array; however, parameter $value of Criteria::__construct() 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

188
        $criteria->add(new \Criteria('poll_id', /** @scrutinizer ignore-type */ $this->pollObj->getVar('poll_id'), '='));
Loading history...
189
        $criteria->setSort('option_id');
190
        $optObjsArray = $this->optionHandler->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 . "%'>";
199
            } else {
200
                $options[$i]['image'] = '';
201
            }
202
203
            /* setup module config handler - required since this is called by newbb too */
204
            /** @var \XoopsModuleHandler $moduleHandler */
205
            $moduleHandler = \xoops_getHandler('module');
206
            $configHandler = \xoops_getHandler('config');
207
            $xp_module      = $moduleHandler->getByDirname('xoopspoll');
208
            $module_id      = $xp_module->getVar('mid');
209
            $xp_config      = $configHandler->getConfigsByCat(0, $module_id);
0 ignored issues
show
Bug introduced by
The method getConfigsByCat() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

209
            /** @scrutinizer ignore-call */ 
210
            $xp_config      = $configHandler->getConfigsByCat(0, $module_id);
Loading history...
210
211
            if ($xp_config['disp_vote_nums']) {
212
                $options[$i]['percent'] = \sprintf(' %01.1f%% (%d)', $percent, $optionVars['option_count']);
213
            } else {
214
                $options[$i]['percent'] = \sprintf(' %01.1f%%', $percent);
215
            }
216
            $options[$i]['text']  = $optionVars['option_text'];
217
            $options[$i]['total'] = $optionVars['option_count'];
218
            $options[$i]['value'] = (int) $percent;
219
            ++$i;
220
            unset($optionVars);
221
        }
222
        $uid = (isset($GLOBALS['xoopsUser'])
223
                 && \is_object($GLOBALS['xoopsUser'])) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
224
            $vote = null;
225
        if (!$this->pollObj->hasExpired() && $this->pollObj->isAllowedToVote()
0 ignored issues
show
Bug introduced by
The method hasExpired() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Xoopspoll\Poll. ( Ignorable by Annotation )

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

225
        if (!$this->pollObj->/** @scrutinizer ignore-call */ hasExpired() && $this->pollObj->isAllowedToVote()
Loading history...
226
            && !$this->logHandler->hasVoted($this->pollObj->getVar('poll_id'), \xoops_getenv('REMOTE_ADDR'), $uid)) {
227
            $vote = "<a href='" . $GLOBALS['xoops']->url('modules/xoopspoll/index.php') . '?poll_id=' . $this->pollObj->getVar('poll_id') . "'>" . \_MD_XOOPSPOLL_VOTE_NOW . '</a>';
228
        }
229
        if ($xp_config['disp_vote_nums']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xp_config seems to be defined by a foreach iteration on line 193. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
230
            $totalVotes  = \sprintf(\_MD_XOOPSPOLL_TOTALVOTES, $total);
0 ignored issues
show
Bug introduced by
It seems like $total 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

230
            $totalVotes  = \sprintf(\_MD_XOOPSPOLL_TOTALVOTES, /** @scrutinizer ignore-type */ $total);
Loading history...
231
            $totalVoters = \sprintf(\_MD_XOOPSPOLL_TOTALVOTERS, $this->pollObj->getVar('voters'));
232
        } else {
233
            $totalVotes = $totalVoters = '';
234
        }
235
236
        $tpl->assign(
237
            'poll',
238
            [
239
            'question'    => $myts->htmlSpecialChars($this->pollObj->getVar('question')),
240
            'end_text'    => $xuEndFormatted,
241
            'start_text'  => $xuStartFormatted,
242
            'totalVotes'  => $totalVotes,
243
            'totalVoters' => $totalVoters,
244
            'vote'        => $vote,
245
            'options'     => $options,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $options seems to be defined by a foreach iteration on line 193. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
246
                'description' => $this->pollObj->getVar('description'), //allow html
247
            ]
248
        );
249
    }
250
}
251