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

XoopspollOptionHandler::getAllByPollId()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 8
nop 3
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
1
<?php
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
 * Poll Option class for the XoopsPoll Module
27
 *
28
 * @copyright ::  {@link http://xoops.org/ XOOPS Project}
29
 * @license   ::  {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
30
 * @package   ::  xoopspoll
31
 * @subpackage::  class
32
 * @since     ::  1.0
33
 * @author    ::  {@link http://www.myweb.ne.jp/ Kazumi Ono (AKA onokazu)}
34
 */
35
// 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...
36
37
class XoopspollOption extends XoopsObject
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...
38
{
39
    /**
40
     * database connection object
41
     * @var XoopsDatabasefactory
42
     */
43
    //    protected $db;
44
    /**
45
     * holds option object
46
     * @var XoopspollOption
47
     */
48
    protected $option;
49
    /**
50
     * Option Handler to be used to manipulate poll options
51
     * @var XoopspollOptionHandler
52
     */
53
    protected $optHandler;
54
55
    // constructor
56
    /**
57
     * @param int|null $id poll id
58
     */
59
    public function __construct($id = null)
60
    {
61
        parent::__construct();
62
        xoops_load('constants', 'xoopspoll');
63
        //        $this->db = XoopsDatabaseFactory::getDatabaseConnection();
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
64
        $this->initVar('option_id', XOBJ_DTYPE_INT, null, false);
65
        $this->initVar('poll_id', XOBJ_DTYPE_INT, null, true);
66
        $this->initVar('option_text', XOBJ_DTYPE_TXTBOX, null, true, 255);
67
        $this->initVar('option_count', XOBJ_DTYPE_INT, 0, false);
68
        $this->initVar('option_color', XOBJ_DTYPE_OTHER, null, false);
69
70
        /**
71
         * {@internal The following is provided for backward compatibility with newbb/xforum}
72
         */
73
        $this->optHandler = xoops_getModuleHandler('option', 'xoopspoll');
74
        if (!empty($id)) {
75
            if (is_array($id)) {
76
                $this->option = $this->optHandler->create();
77
                $this->option->assignVars($id);
78
            } else {
79
                $this->option = $this->optHandler->get($id);
80
            }
81
        }
82
    }
83
84
    /**
85
     * @param int|null $id poll id
86
     * @return void
87
     * @deprecated since PHP4 died - use __construct
88
     */
89
    public function XoopspollOption($id = null)
90
    {
91
        $this->__construct($id);
92
    }
93
94
    /**
95
     * The following method is provided for backward compatibility with newbb/xforum
96
     * Stores object into the database
97
     * @uses XoopsPersistableObjectHandler::insert
98
     * @return mixed
99
     * @deprecated since Xoopspoll 1.40, please @see XoopspollOptionHandler & @see XoopspollOption
100
     */
101
    public function store()
0 ignored issues
show
Coding Style introduced by
store 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
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use XoopspollPoll and XoopspollPollHandler classes instead.');
104
105
        return $this->optHandler->insert($this->option);
106
    }
107
108
    /**
109
     * Delete all the poll options for a specific poll
110
     *
111
     * @uses XoopsPersistableObjectHandler::deleteAll
112
     * @param  int   $pid is used to delete all options by this id
113
     * @return mixed results of deleting objects from database
114
     */
115 View Code Duplication
    public function deleteByPollId($pid)
0 ignored issues
show
Duplication introduced by
This method 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...
Coding Style introduced by
deleteByPollId 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...
116
    {
117
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use XoopspollPollHandler::' . __METHOD__ . ' instead.');
118
        $criteria    = new Criteria('poll_id', (int)$pid, '=');
119
120
        return $this->optHandler->deleteAll($criteria);
121
    }
122
123
    /**
124
     * Get all options for a particular poll
125
     *
126
     * @uses XoopsPersistableObjectHandler::getAll
127
     * @param  int $pid poll id
128
     * @return mixed   results of getting objects from database
129
     */
130 View Code Duplication
    public function getAllByPollId($pid)
0 ignored issues
show
Duplication introduced by
This method 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...
Coding Style introduced by
getAllByPollId 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...
131
    {
132
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use XoopspollPollHandler::' . __METHOD__ . ' instead.');
133
        $criteria    = new Criteria('poll_id', (int)$pid, '=');
134
135
        return $this->optHandler->getAll($criteria);
136
    }
137
138
    /**
139
     * Reset the poll's options vote count
140
     *
141
     * @param int $pid poll id
142
     * @uses XoopsPersistableObjectHandler::updateAll
143
     * @return mixed results of the object(s) update
144
     */
145 View Code Duplication
    public function resetCountByPollId($pid)
0 ignored issues
show
Duplication introduced by
This method 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...
Coding Style introduced by
resetCountByPollId 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...
146
    {
147
        $GLOBALS['xoopsLogger']->addDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated since Xoopspoll 1.40, please use XoopspollPollHandler::' . __METHOD__ . ' instead.');
148
        $criteria    = new Criteria('poll_id', (int)$pid, '=');
149
150
        return $this->optHandler->updateAll('option_count', 0, $criteria);
151
    }
152
}
153
154
/**
155
 * Class XoopspollOptionHandler
156
 */
157
class XoopspollOptionHandler extends XoopsPersistableObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
158
{
159
    /**
160
     * XoopspollPollOptionHandler::__construct()
161
     *
162
     * @param null|XoopsDatabase $db database
163
     **/
164
    public function __construct(XoopsDatabase $db)
165
    {
166
        xoops_load('constants', 'xoopspoll');
167
        parent::__construct($db, 'xoopspoll_option', 'XoopspollOption', 'option_id', 'option_text');
168
    }
169
170
    /**
171
     * XoopspollOptionHandler::XoopspollOptionHandler()
172
     *
173
     * @param mixed $db database
174
     * @return void
175
     * @deprecated use __construct()
176
     **/
177
    public function XoopspollOptionHandler($db)
178
    {
179
        $this->__construct($db);
180
    }
181
182
    /**
183
     *
184
     * Update the option vote count for a Option Object
185
     * @uses xoops_getModuleHandler
186
     * @uses XoopsPersistableObjectHandler::insert
187
     * @param  mixed $optionObj is an option object to update
188
     * @return mixed results @see XoopsPersistibleObjectHandler
189
     */
190
    public function updateCount($optionObj)
191
    {
192
        $status = false;
193
        static $logHandler;
194
        if ($optionObj instanceof XoopspollOption) {
195
            $option_id = $optionObj->getVar('option_id');
196
            if (!isset($logHandler)) {
197
                $logHandler = xoops_getModuleHandler('log', 'xoopspoll');
198
            }
199
            $votes = $logHandler->getTotalVotesByOptionId($option_id);
200
            $optionObj->setVar('option_count', $votes);
201
            $status = $this->insert($optionObj);
202
        }
203
204
        return $status;
205
    }
206
207
    /**
208
     *
209
     * Gets all options for poll ID
210
     *
211
     * @param  int    $pid     poll id
212
     * @param  string $sortby  column name to sort on
213
     * @param  string $orderby sort order
214
     * @return array  an array of Option objects
215
     * @uses CriteriaCompo
216
     * @uses XoopsPersistableObjectHandler::deleteAll
217
     */
218
    public function getAllByPollId($pid = 0, $sortby = 'option_id', $orderby = 'ASC')
219
    {
220
        //$criteria = new CriteriaCompo();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
221
        $criteria = new Criteria('poll_id', (int)$pid, '=');
222
        if (!empty($sortby)) {
223
            $criteria->setSort($sortby);
224
        }
225
        if (!empty($orderby)) {
226
            $criteria->setOrder($orderby);
227
        }
228
        $optionObjs = $this->getAll($criteria);
229
        if (empty($optionObjs)) {
230
            $optionObjs = array();
231
        }
232
233
        return $optionObjs;
234
    }
235
236
    /**
237
     * Deletes the option for selected poll
238
     *
239
     * @param int $pid poll id
240
     * @uses Criteria
241
     * @uses XoopsPersistableObjectHandler::deleteAll
242
     * @return bool $success
243
     */
244
    public function deleteByPollId($pid = 0)
245
    {
246
        $success = $this->deleteAll(new Criteria('poll_id', (int)$pid, '='));
247
248
        return $success;
249
    }
250
251
    /**
252
     * Reset the vote counts for the options for selected poll
253
     *
254
     * @param int $pid poll id
255
     * @uses Criteria
256
     * @uses XoopsPersistableObjectHandler::updateAll
257
     * @return bool $success
258
     */
259
    public function resetCountByPollId($pid = 0)
260
    {
261
        $success = $this->updateAll('option_count', 0, new Criteria('poll_id', (int)$pid, '='));
262
263
        return $success;
264
    }
265
266
    /**
267
     * Generates an html select box with options
268
     *
269
     * @param  mixed  $pid the select box is created for this poll id
270
     * @return string html select box
0 ignored issues
show
Documentation introduced by
Should the return type not be XoopsFormElementTray?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
271
     */
272
    public function renderOptionFormTray($pid = 0)
0 ignored issues
show
Coding Style introduced by
renderOptionFormTray 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...
273
    {
274
        xoops_load('xoopsformloader');
275
        $pid            = (int)$pid;
276
        $barcolor_array = XoopsLists::getImgListAsArray($GLOBALS['xoops']->path('modules/xoopspoll/assets/images/colorbars/'));
277
278
        /**
279
         * get all the options for this poll & add some blank options to allow adding more
280
         */
281
        if (0 === $pid) {
282
            $optionObjs = array();
283
            $newOpts = (2 * XoopspollConstants::NUM_ADDTL_OPTIONS);
284
        } else {
285
            $optionObjs = $this->getAllByPollId($pid);
286
            $newOpts    = XoopspollConstants::NUM_ADDTL_OPTIONS;
287
        }
288
        $thisBarColorArray = $barcolor_array;
289
        unset($thisBarColorArray['blank.gif']);
290
        for ($i = 0; $i < $newOpts; ++$i) {
291
            $thisObj    = $this->create();
292
            $currentBar = array_rand($thisBarColorArray);
293
            unset($thisBarColorArray[$currentBar]);
294
            $thisObj->setVar('option_color', $currentBar);
295
            $optionObjs[] = $thisObj;
296
            if (empty($thisBarColorArray)) {
297
                $thisBarColorArray = $barcolor_array;
298
                unset($thisBarColorArray['blank.gif']);
299
            }
300
            unset($thisObj);
301
        }
302
        /**
303
         * add the options to the form
304
         */
305
        $optionTray = new XoopsFormElementTray(_AM_XOOPSPOLL_POLLOPTIONS, '');
306
        $i          = 0;
307
        foreach ($optionObjs as $optObj) {
308
            $colorSelect = new XoopsFormSelect('', "option_color[{$i}]", $optObj->getVar('option_color'));
309
            $colorSelect->addOptionArray($barcolor_array);
310
            $colorSelect->setExtra("onchange='showImgSelected(\"option_color_image[{$i}]\", \"option_color[{$i}]\", \"modules/xoopspoll/assets/images/colorbars\", \"\", \"" . $GLOBALS['xoops']->url('') . "\")'");
311
            $colorLabel = new XoopsFormLabel('', "<img src='" . $GLOBALS['xoops']->url('modules/xoopspoll' . '/assets/images/colorbars/' . $optObj->getVar('option_color')) . "'" . " name='option_color_image[{$i}]'" . " id='option_color_image[{$i}]'"
312
                                                 . " style='width: 30px; height: 15px;'" . " class='alignmiddle'" . " alt='' /><br>");
313
314
            $optionTray->addElement(new XoopsFormText('', "option_text[{$i}]", 50, 255, $optObj->getVar('option_text')));
315
            $optionTray->addElement(new XoopsFormHidden("option_id[{$i}]", $optObj->getVar('option_id')));
316
            $optionTray->addElement($colorSelect);
317
            $optionTray->addElement($colorLabel);
318
            unset($colorSelect, $colorLabel);
319
            ++$i;
320
        }
321
322
        return $optionTray;
323
    }
324
}
325