Completed
Push — master ( bf34f3...88111b )
by Michael
03:08
created

SmartObjectTable::render()   F

Complexity

Conditions 42
Paths > 20000

Size

Total Lines 222
Code Lines 145

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 42
eloc 145
nc 44098560
nop 2
dl 0
loc 222
rs 2
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 namespace XoopsModules\Smartobject;
2
3
/**
4
 * Contains the classes responsible for displaying a simple table filled with records of SmartObjects
5
 *
6
 * @license    GNU
7
 * @author     marcan <[email protected]>
8
 * @link       http://smartfactory.ca The SmartFactory
9
 * @package    SmartObject
10
 * @subpackage SmartObjectTable
11
 */
12
13
use CriteriaElement;
14
use XoopsModules\Smartobject;
15
16
17
/**
18
 * SmartObjectTable base class
19
 *
20
 * Base class representing a table for displaying SmartObjects
21
 *
22
 * @package SmartObject
23
 * @author  marcan <[email protected]>
24
 * @link    http://smartfactory.ca The SmartFactory
25
 */
26
class SmartObjectTable
27
{
28
    public $_id;
29
    public $_objectHandler;
30
    public $_columns;
31
    public $_criteria;
32
    public $_actions;
33
    public $_objects = false;
34
    public $_aObjects;
35
    public $_custom_actions;
36
    public $_sortsel;
37
    public $_ordersel;
38
    public $_limitsel;
39
    public $_filtersel;
40
    public $_filterseloptions;
41
    public $_filtersel2;
42
    public $_filtersel2options;
43
    public $_filtersel2optionsDefault;
44
45
    public $_tempObject;
46
    public $_tpl;
47
    public $_introButtons;
48
    public $_quickSearch            = false;
49
    public $_actionButtons          = false;
50
    public $_head_css_class         = 'bg3';
51
    public $_hasActions             = false;
52
    public $_userSide               = false;
53
    public $_printerFriendlyPage    = false;
54
    public $_tableHeader            = false;
55
    public $_tableFooter            = false;
56
    public $_showActionsColumnTitle = true;
57
    public $_isTree                 = false;
58
    public $_showFilterAndLimit     = true;
59
    public $_enableColumnsSorting   = true;
60
    public $_customTemplate         = false;
61
    public $_withSelectedActions    = [];
62
63
    /**
64
     * Constructor
65
     *
66
     * @param SmartPersistableObjectHandler $objectHandler {@link SmartPersistableObjectHandler}
67
     * @param CriteriaElement               $criteria
68
     * @param array                         $actions       array representing the actions to offer
69
     *
70
     * @param bool                          $userSide
71
     */
72
    public function __construct(
73
        SmartPersistableObjectHandler $objectHandler,
74
        CriteriaElement $criteria = null,
75
        $actions = ['edit', 'delete'],
76
        $userSide = false
77
    ) {
78
        $this->_id            = $objectHandler->className;
79
        $this->_objectHandler = $objectHandler;
80
81
        if (!$criteria) {
82
            $criteria = new \CriteriaCompo();
83
        }
84
        $this->_criteria       = $criteria;
85
        $this->_actions        = $actions;
86
        $this->_custom_actions = [];
87
        $this->_userSide       = $userSide;
88
        if ($userSide) {
89
            $this->_head_css_class = 'head';
90
        }
91
    }
92
93
    /**
94
     * @param      $op
95
     * @param bool $caption
96
     * @param bool $text
97
     */
98
    public function addActionButton($op, $caption = false, $text = false)
99
    {
100
        $action                 = [
101
            'op'      => $op,
102
            'caption' => $caption,
103
            'text'    => $text
104
        ];
105
        $this->_actionButtons[] = $action;
106
    }
107
108
    /**
109
     * @param $columnObj
110
     */
111
    public function addColumn($columnObj)
112
    {
113
        $this->_columns[] = $columnObj;
114
    }
115
116
    /**
117
     * @param $name
118
     * @param $location
119
     * @param $value
120
     */
121
    public function addIntroButton($name, $location, $value)
122
    {
123
        $introButton             = [];
124
        $introButton['name']     = $name;
125
        $introButton['location'] = $location;
126
        $introButton['value']    = $value;
127
        $this->_introButtons[]   = $introButton;
128
        unset($introButton);
129
    }
130
131
    public function addPrinterFriendlyLink()
132
    {
133
        $current_urls               = smart_getCurrentUrls();
134
        $current_url                = $current_urls['full'];
135
        $this->_printerFriendlyPage = $current_url . '&print';
0 ignored issues
show
Documentation Bug introduced by
The property $_printerFriendlyPage was declared of type boolean, but $current_url . '&print' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
136
    }
137
138
    /**
139
     * @param        $fields
140
     * @param string $caption
141
     */
142
    public function addQuickSearch($fields, $caption = _CO_SOBJECT_QUICK_SEARCH)
143
    {
144
        $this->_quickSearch = ['fields' => $fields, 'caption' => $caption];
0 ignored issues
show
Documentation Bug introduced by
It seems like array('fields' => $fields, 'caption' => $caption) of type array<string,?,{"fields":"?","caption":"string"}> is incompatible with the declared type boolean of property $_quickSearch.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
145
    }
146
147
    /**
148
     * @param $content
149
     */
150
    public function addHeader($content)
151
    {
152
        $this->_tableHeader = $content;
153
    }
154
155
    /**
156
     * @param $content
157
     */
158
    public function addFooter($content)
159
    {
160
        $this->_tableFooter = $content;
161
    }
162
163
    /**
164
     * @param $caption
165
     */
166
    public function addDefaultIntroButton($caption)
167
    {
168
        $this->addIntroButton($this->_objectHandler->_itemname, $this->_objectHandler->_page . '?op=mod', $caption);
169
    }
170
171
    /**
172
     * @param $method
173
     */
174
    public function addCustomAction($method)
175
    {
176
        $this->_custom_actions[] = $method;
177
    }
178
179
    /**
180
     * @param $default_sort
181
     */
182
    public function setDefaultSort($default_sort)
183
    {
184
        $this->_sortsel = $default_sort;
185
    }
186
187
    /**
188
     * @return string
189
     */
190 View Code Duplication
    public function getDefaultSort()
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...
191
    {
192
        if ($this->_sortsel) {
193
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_sortsel', $this->_sortsel);
194
        } else {
195
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_sortsel', $this->_objectHandler->identifierName);
196
        }
197
    }
198
199
    /**
200
     * @param $default_order
201
     */
202
    public function setDefaultOrder($default_order)
203
    {
204
        $this->_ordersel = $default_order;
205
    }
206
207
    /**
208
     * @return string
209
     */
210 View Code Duplication
    public function getDefaultOrder()
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...
211
    {
212
        if ($this->_ordersel) {
213
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_ordersel', $this->_ordersel);
214
        } else {
215
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_ordersel', 'ASC');
216
        }
217
    }
218
219
    /**
220
     * @param array $actions
221
     */
222
    public function addWithSelectedActions($actions = [])
223
    {
224
        $this->addColumn(new SmartObjectColumn('checked', 'center', 20, false, false, '&nbsp;'));
0 ignored issues
show
Documentation introduced by
20 is of type integer, but the function expects a boolean.

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...
Documentation introduced by
'&nbsp;' is of type string, but the function expects a boolean.

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...
225
        $this->_withSelectedActions = $actions;
226
    }
227
228
    /**
229
     * Adding a filter in the table
230
     *
231
     * @param string $key    key to the field that will be used for sorting
232
     * @param string $method method of the handler that will be called to populate the options when this filter is selected
233
     * @param bool   $default
234
     */
235
    public function addFilter($key, $method, $default = false)
236
    {
237
        $this->_filterseloptions[$key]   = $method;
238
        $this->_filtersel2optionsDefault = $default;
239
    }
240
241
    /**
242
     * @param $default_filter
243
     */
244
    public function setDefaultFilter($default_filter)
245
    {
246
        $this->_filtersel = $default_filter;
247
    }
248
249
    public function isForUserSide()
250
    {
251
        $this->_userSide = true;
252
    }
253
254
    /**
255
     * @param $template
256
     */
257
    public function setCustomTemplate($template)
258
    {
259
        $this->_customTemplate = $template;
260
    }
261
262
    public function setSortOrder()
263
    {
264
        $this->_sortsel = isset($_GET[$this->_objectHandler->_itemname . '_' . 'sortsel']) ? $_GET[$this->_objectHandler->_itemname . '_' . 'sortsel'] : $this->getDefaultSort();
265
        //$this->_sortsel = isset($_POST['sortsel']) ? $_POST['sortsel']: $this->_sortsel;
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...
266
        smart_setCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_sortsel', $this->_sortsel);
267
        $fieldsForSorting = $this->_tempObject->getFieldsForSorting($this->_sortsel);
0 ignored issues
show
Unused Code introduced by
$fieldsForSorting is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
268
269
        if (isset($this->_tempObject->vars[$this->_sortsel]['itemName'])
270
            && $this->_tempObject->vars[$this->_sortsel]['itemName']) {
271
            $this->_criteria->setSort($this->_tempObject->vars[$this->_sortsel]['itemName'] . '.' . $this->_sortsel);
272
        } else {
273
            $this->_criteria->setSort($this->_objectHandler->_itemname . '.' . $this->_sortsel);
274
        }
275
276
        $this->_ordersel = isset($_GET[$this->_objectHandler->_itemname . '_' . 'ordersel']) ? $_GET[$this->_objectHandler->_itemname . '_' . 'ordersel'] : $this->getDefaultOrder();
277
        //$this->_ordersel = isset($_POST['ordersel']) ? $_POST['ordersel']:$this->_ordersel;
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...
278
        smart_setCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_ordersel', $this->_ordersel);
279
        $ordersArray = $this->getOrdersArray();
0 ignored issues
show
Unused Code introduced by
$ordersArray is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
280
        $this->_criteria->setOrder($this->_ordersel);
281
    }
282
283
    /**
284
     * @param $id
285
     */
286
    public function setTableId($id)
287
    {
288
        $this->_id = $id;
289
    }
290
291
    /**
292
     * @param $objects
293
     */
294
    public function setObjects($objects)
295
    {
296
        $this->_objects = $objects;
297
    }
298
299
    public function createTableRows()
300
    {
301
        $this->_aObjects = [];
302
303
        $doWeHaveActions = false;
304
305
        $objectclass = 'odd';
306
        if (count($this->_objects) > 0) {
307
            foreach ($this->_objects as $object) {
0 ignored issues
show
Bug introduced by
The expression $this->_objects of type boolean is not traversable.
Loading history...
308
                $aObject = [];
309
310
                $i = 0;
311
312
                $aColumns = [];
313
314
                foreach ($this->_columns as $column) {
315
                    $aColumn = [];
316
317 View Code Duplication
                    if (0 == $i) {
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...
318
                        $class = 'head';
319
                    } elseif (0 == $i % 2) {
320
                        $class = 'even';
321
                    } else {
322
                        $class = 'odd';
323
                    }
324
                    if (method_exists($object, 'initiateCustomFields')) {
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...
325
                        //$object->initiateCustomFields();
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
326
                    }
327
                    if ('checked' === $column->_keyname) {
328
                        $value = '<input type ="checkbox" name="selected_smartobjects[]" value="' . $object->id() . '">';
329
                    } elseif ($column->_customMethodForValue
330
                              && method_exists($object, $column->_customMethodForValue)) {
331
                        $method = $column->_customMethodForValue;
332
                        if ($column->_param) {
333
                            $value = $object->$method($column->_param);
334
                        } else {
335
                            $value = $object->$method();
336
                        }
337 View Code Duplication
                    } else {
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...
338
                        /**
339
                         * If the column is the identifier, then put a link on it
340
                         */
341
                        if ($column->getKeyName() == $this->_objectHandler->identifierName) {
342
                            $value = $object->getItemLink();
343
                        } else {
344
                            $value = $object->getVar($column->getKeyName());
345
                        }
346
                    }
347
348
                    $aColumn['value'] = $value;
349
                    $aColumn['class'] = $class;
350
                    $aColumn['width'] = $column->getWidth();
351
                    $aColumn['align'] = $column->getAlign();
352
353
                    $aColumns[] = $aColumn;
354
                    ++$i;
355
                }
356
357
                $aObject['columns'] = $aColumns;
358
                $aObject['id']      = $object->id();
359
360
                $objectclass = ('even' === $objectclass) ? 'odd' : 'even';
361
362
                $aObject['class'] = $objectclass;
363
364
                $actions = [];
365
366
                // Adding the custom actions if any
367
                foreach ($this->_custom_actions as $action) {
368
                    if (method_exists($object, $action)) {
369
                        $actions[] = $object->$action();
370
                    }
371
                }
372
373
                require_once SMARTOBJECT_ROOT_PATH . 'class/smartobjectcontroller.php';
374
                $controller = new SmartObjectController($this->_objectHandler);
375
376 View Code Duplication
                if ((!is_array($this->_actions)) || in_array('edit', $this->_actions)) {
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...
377
                    $actions[] = $controller->getEditItemLink($object, false, true, $this->_userSide);
378
                }
379 View Code Duplication
                if ((!is_array($this->_actions)) || in_array('delete', $this->_actions)) {
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...
380
                    $actions[] = $controller->getDeleteItemLink($object, false, true, $this->_userSide);
381
                }
382
                $aObject['actions'] = $actions;
383
384
                $this->_tpl->assign('smartobject_actions_column_width', count($actions) * 30);
385
386
                $doWeHaveActions = $doWeHaveActions ? true : count($actions) > 0;
387
388
                $this->_aObjects[] = $aObject;
389
            }
390
            $this->_tpl->assign('smartobject_objects', $this->_aObjects);
391
        } else {
392
            $colspan = count($this->_columns) + 1;
393
            $this->_tpl->assign('smartobject_colspan', $colspan);
394
        }
395
        $this->_hasActions = $doWeHaveActions;
396
    }
397
398
    /**
399
     * @param  bool $debug
400
     * @return mixed
401
     */
402
    public function fetchObjects($debug = false)
403
    {
404
        return $this->_objectHandler->getObjects($this->_criteria, true, true, false, $debug);
405
    }
406
407
    /**
408
     * @return string
409
     */
410 View Code Duplication
    public function getDefaultFilter()
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...
411
    {
412
        if ($this->_filtersel) {
413
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_filtersel', $this->_filtersel);
414
        } else {
415
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_filtersel', 'default');
416
        }
417
    }
418
419
    /**
420
     * @return array|bool
421
     */
422
    public function getFiltersArray()
423
    {
424
        $ret               = [];
425
        $field             = [];
426
        $field['caption']  = _CO_OBJ_NONE;
427
        $field['selected'] = '';
428
        $ret['default']    = $field;
429
        unset($field);
430
431
        if ($this->_filterseloptions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->_filterseloptions of type array<string,string> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
432
            foreach ($this->_filterseloptions as $key => $value) {
433
                $field = [];
434
                if (is_array($value)) {
435
                    $field['caption']  = $key;
436
                    $field['selected'] = $this->_filtersel == $key ? 'selected' : '';
437
                } else {
438
                    $field['caption']  = $this->_tempObject->vars[$key]['form_caption'];
439
                    $field['selected'] = $this->_filtersel == $key ? 'selected' : '';
440
                }
441
                $ret[$key] = $field;
442
                unset($field);
443
            }
444
        } else {
445
            $ret = false;
446
        }
447
448
        return $ret;
449
    }
450
451
    /**
452
     * @param $default_filter2
453
     */
454
    public function setDefaultFilter2($default_filter2)
455
    {
456
        $this->_filtersel2 = $default_filter2;
457
    }
458
459
    /**
460
     * @return string
461
     */
462
    public function getDefaultFilter2()
463
    {
464
        if ($this->_filtersel2) {
465
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_filtersel2', $this->_filtersel2);
466
        } else {
467
            return smart_getCookieVar($_SERVER['PHP_SELF'] . '_filtersel2', 'default');
468
        }
469
    }
470
471
    /**
472
     * @return array
473
     */
474
    public function getFilters2Array()
475
    {
476
        $ret = [];
477
478
        foreach ($this->_filtersel2options as $key => $value) {
479
            $field             = [];
480
            $field['caption']  = $value;
481
            $field['selected'] = $this->_filtersel2 == $key ? 'selected' : '';
482
            $ret[$key]         = $field;
483
            unset($field);
484
        }
485
486
        return $ret;
487
    }
488
489
    /**
490
     * @param $limitsArray
491
     * @param $params_of_the_options_sel
492
     */
493
    public function renderOptionSelection($limitsArray, $params_of_the_options_sel)
0 ignored issues
show
Unused Code introduced by
The parameter $params_of_the_options_sel is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
494
    {
495
        // Rendering the form to select options on the table
496
        $current_urls = smart_getCurrentUrls();
497
        $current_url  = $current_urls['full'];
498
499
        /**
500
         * What was $params_of_the_options_sel doing again ?
501
         */
502
        //$this->_tpl->assign('smartobject_optionssel_action', $_SERVER['PHP_SELF'] . "?" . implode('&', $params_of_the_options_sel));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
503
        $this->_tpl->assign('smartobject_optionssel_action', $current_url);
504
        $this->_tpl->assign('smartobject_optionssel_limitsArray', $limitsArray);
505
    }
506
507
    /**
508
     * @return array
509
     */
510
    public function getLimitsArray()
511
    {
512
        $ret                    = [];
513
        $ret['all']['caption']  = _CO_SOBJECT_LIMIT_ALL;
514
        $ret['all']['selected'] = ('all' === $this->_limitsel) ? 'selected' : '';
515
516
        $ret['5']['caption']  = '5';
517
        $ret['5']['selected'] = ('5' == $this->_limitsel) ? 'selected' : '';
518
519
        $ret['10']['caption']  = '10';
520
        $ret['10']['selected'] = ('10' == $this->_limitsel) ? 'selected' : '';
521
522
        $ret['15']['caption']  = '15';
523
        $ret['15']['selected'] = ('15' == $this->_limitsel) ? 'selected' : '';
524
525
        $ret['20']['caption']  = '20';
526
        $ret['20']['selected'] = ('20' == $this->_limitsel) ? 'selected' : '';
527
528
        $ret['25']['caption']  = '25';
529
        $ret['25']['selected'] = ('25' == $this->_limitsel) ? 'selected' : '';
530
531
        $ret['30']['caption']  = '30';
532
        $ret['30']['selected'] = ('30' == $this->_limitsel) ? 'selected' : '';
533
534
        $ret['35']['caption']  = '35';
535
        $ret['35']['selected'] = ('35' == $this->_limitsel) ? 'selected' : '';
536
537
        $ret['40']['caption']  = '40';
538
        $ret['40']['selected'] = ('40' == $this->_limitsel) ? 'selected' : '';
539
540
        return $ret;
541
    }
542
543
    /**
544
     * @return bool
545
     */
546
    public function getObjects()
547
    {
548
        return $this->_objects;
549
    }
550
551
    public function hideActionColumnTitle()
552
    {
553
        $this->_showActionsColumnTitle = false;
554
    }
555
556
    public function hideFilterAndLimit()
557
    {
558
        $this->_showFilterAndLimit = false;
559
    }
560
561
    /**
562
     * @return array
563
     */
564
    public function getOrdersArray()
565
    {
566
        $ret                    = [];
567
        $ret['ASC']['caption']  = _CO_SOBJECT_SORT_ASC;
568
        $ret['ASC']['selected'] = ('ASC' === $this->_ordersel) ? 'selected' : '';
569
570
        $ret['DESC']['caption']  = _CO_SOBJECT_SORT_DESC;
571
        $ret['DESC']['selected'] = ('DESC' === $this->_ordersel) ? 'selected' : '';
572
573
        return $ret;
574
    }
575
576
    /**
577
     * @return mixed|string|void
578
     */
579
    public function renderD()
580
    {
581
        return $this->render(false, true);
582
    }
583
584
    public function renderForPrint()
585
    {
586
    }
587
588
    /**
589
     * @param  bool $fetchOnly
590
     * @param  bool $debug
591
     * @return mixed|string|void
592
     */
593
    public function render($fetchOnly = false, $debug = false)
594
    {
595
        require_once XOOPS_ROOT_PATH . '/class/template.php';
596
597
        $this->_tpl = new \XoopsTpl();
598
599
        /**
600
         * We need access to the vars of the SmartObject for a few things in the table creation.
601
         * Since we may not have a SmartObject to look into now, let's create one for this purpose
602
         * and we will free it after
603
         */
604
        $this->_tempObject = $this->_objectHandler->create();
605
606
        $this->_criteria->setStart(isset($_GET['start' . $this->_objectHandler->keyName]) ? (int)$_GET['start' . $this->_objectHandler->keyName] : 0);
607
608
        $this->setSortOrder();
609
610
        if (!$this->_isTree) {
611
            $this->_limitsel = isset($_GET['limitsel']) ? $_GET['limitsel'] : smart_getCookieVar($_SERVER['PHP_SELF'] . '_limitsel', '15');
612
        } else {
613
            $this->_limitsel = 'all';
614
        }
615
616
        $this->_limitsel = isset($_POST['limitsel']) ? $_POST['limitsel'] : $this->_limitsel;
617
        smart_setCookieVar($_SERVER['PHP_SELF'] . '_limitsel', $this->_limitsel);
618
        $limitsArray = $this->getLimitsArray();
619
        $this->_criteria->setLimit($this->_limitsel);
620
621
        $this->_filtersel = isset($_GET['filtersel']) ? $_GET['filtersel'] : $this->getDefaultFilter();
622
        $this->_filtersel = isset($_POST['filtersel']) ? $_POST['filtersel'] : $this->_filtersel;
623
        smart_setCookieVar($_SERVER['PHP_SELF'] . '_' . $this->_id . '_filtersel', $this->_filtersel);
624
        $filtersArray = $this->getFiltersArray();
625
626
        if ($filtersArray) {
627
            $this->_tpl->assign('smartobject_optionssel_filtersArray', $filtersArray);
628
        }
629
630
        // Check if the selected filter is defined and if so, create the selfilter2
631
        if (isset($this->_filterseloptions[$this->_filtersel])) {
632
            // check if method associate with this filter exists in the handler
633
            if (is_array($this->_filterseloptions[$this->_filtersel])) {
634
                $filter = $this->_filterseloptions[$this->_filtersel];
635
                $this->_criteria->add($filter['criteria']);
636
            } else {
637
                if (method_exists($this->_objectHandler, $this->_filterseloptions[$this->_filtersel])) {
638
639
                    // then we will create the selfilter2 options by calling this method
640
                    $method                   = $this->_filterseloptions[$this->_filtersel];
641
                    $this->_filtersel2options = $this->_objectHandler->$method();
642
643
                    $this->_filtersel2 = isset($_GET['filtersel2']) ? $_GET['filtersel2'] : $this->getDefaultFilter2();
644
                    $this->_filtersel2 = isset($_POST['filtersel2']) ? $_POST['filtersel2'] : $this->_filtersel2;
645
646
                    $filters2Array = $this->getFilters2Array();
647
                    $this->_tpl->assign('smartobject_optionssel_filters2Array', $filters2Array);
648
649
                    smart_setCookieVar($_SERVER['PHP_SELF'] . '_filtersel2', $this->_filtersel2);
650
                    if ('default' !== $this->_filtersel2) {
651
                        $this->_criteria->add(new \Criteria($this->_filtersel, $this->_filtersel2));
652
                    }
653
                }
654
            }
655
        }
656
        // Check if we have a quicksearch
657
658
        if (isset($_POST['quicksearch_' . $this->_id]) && '' != $_POST['quicksearch_' . $this->_id]) {
659
            $quicksearch_criteria = new \CriteriaCompo();
660
            if (is_array($this->_quickSearch['fields'])) {
661
                foreach ($this->_quickSearch['fields'] as $v) {
662
                    $quicksearch_criteria->add(new \Criteria($v, '%' . $_POST['quicksearch_' . $this->_id] . '%', 'LIKE'), 'OR');
663
                }
664
            } else {
665
                $quicksearch_criteria->add(new \Criteria($this->_quickSearch['fields'], '%' . $_POST['quicksearch_' . $this->_id] . '%', 'LIKE'));
666
            }
667
            $this->_criteria->add($quicksearch_criteria);
668
        }
669
670
        $this->_objects = $this->fetchObjects($debug);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->fetchObjects($debug) of type array is incompatible with the declared type boolean of property $_objects.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
671
672
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
673
        if ($this->_criteria->getLimit() > 0) {
674
675
            /**
676
             * Geeting rid of the old params
677
             * $new_get_array is an array containing the new GET parameters
678
             */
679
            $new_get_array = [];
680
681
            /**
682
             * $params_of_the_options_sel is an array with all the parameters of the page
683
             * but without the pagenave parameters. This array will be used in the
684
             * OptionsSelection
685
             */
686
            $params_of_the_options_sel = [];
687
688
            $not_needed_params = ['sortsel', 'limitsel', 'ordersel', 'start' . $this->_objectHandler->keyName];
689
            foreach ($_GET as $k => $v) {
690
                if (!in_array($k, $not_needed_params)) {
691
                    $new_get_array[]             = "$k=$v";
692
                    $params_of_the_options_sel[] = "$k=$v";
693
                }
694
            }
695
696
            /**
697
             * Adding the new params of the pagenav
698
             */
699
            $new_get_array[] = 'sortsel=' . $this->_sortsel;
700
            $new_get_array[] = 'ordersel=' . $this->_ordersel;
701
            $new_get_array[] = 'limitsel=' . $this->_limitsel;
702
            $otherParams     = implode('&', $new_get_array);
703
704
            $pagenav = new \XoopsPageNav($this->_objectHandler->getCount($this->_criteria), $this->_criteria->getLimit(), $this->_criteria->getStart(), 'start' . $this->_objectHandler->keyName, $otherParams);
705
            $this->_tpl->assign('smartobject_pagenav', $pagenav->renderNav());
706
        }
707
        $this->renderOptionSelection($limitsArray, $params_of_the_options_sel);
0 ignored issues
show
Bug introduced by
The variable $params_of_the_options_sel 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...
708
709
        // retreive the current url and the query string
710
        $current_urls = smart_getCurrentUrls();
711
        $current_url  = $current_urls['full_phpself'];
712
        $query_string = $current_urls['querystring'];
713
        if ($query_string) {
714
            $query_string = str_replace('?', '', $query_string);
715
        }
716
        $query_stringArray     = explode('&', $query_string);
717
        $new_query_stringArray = [];
718
        foreach ($query_stringArray as $query_string) {
719
            if (false === strpos($query_string, 'sortsel') && false === strpos($query_string, 'ordersel')) {
720
                $new_query_stringArray[] = $query_string;
721
            }
722
        }
723
        $new_query_string = implode('&', $new_query_stringArray);
724
725
        $orderArray                     = [];
726
        $orderArray['ASC']['image']     = 'desc.png';
727
        $orderArray['ASC']['neworder']  = 'DESC';
728
        $orderArray['DESC']['image']    = 'asc.png';
729
        $orderArray['DESC']['neworder'] = 'ASC';
730
731
        $aColumns = [];
732
733
        foreach ($this->_columns as $column) {
734
            $qs_param         = '';
735
            $aColumn          = [];
736
            $aColumn['width'] = $column->getWidth();
737
            $aColumn['align'] = $column->getAlign();
738
            $aColumn['key']   = $column->getKeyName();
739
            if ('checked' === $column->_keyname) {
740
                $aColumn['caption'] = '<input type ="checkbox" id="checkall_smartobjects" name="checkall_smartobjects"' . ' value="checkall_smartobjects" onclick="smartobject_checkall(window.document.form_' . $this->_id . ', \'selected_smartobjects\');">';
741
            } elseif ($column->getCustomCaption()) {
742
                $aColumn['caption'] = $column->getCustomCaption();
743
            } else {
744
                $aColumn['caption'] = isset($this->_tempObject->vars[$column->getKeyName()]['form_caption']) ? $this->_tempObject->vars[$column->getKeyName()]['form_caption'] : $column->getKeyName();
745
            }
746
            // Are we doing a GET sort on this column ?
747
            $getSort = (isset($_GET[$this->_objectHandler->_itemname . '_' . 'sortsel'])
748
                        && $_GET[$this->_objectHandler->_itemname . '_' . 'sortsel'] == $column->getKeyName())
749
                       || ($this->_sortsel == $column->getKeyName());
750
            $order   = isset($_GET[$this->_objectHandler->_itemname . '_' . 'ordersel']) ? $_GET[$this->_objectHandler->_itemname . '_' . 'ordersel'] : 'DESC';
751
752
            if (isset($_REQUEST['quicksearch_' . $this->_id]) && '' != $_REQUEST['quicksearch_' . $this->_id]) {
753
                $qs_param = '&quicksearch_' . $this->_id . '=' . $_REQUEST['quicksearch_' . $this->_id];
754
            }
755
            if (!$this->_enableColumnsSorting || 'checked' === $column->_keyname || !$column->isSortable()) {
756
                $aColumn['caption'] = $aColumn['caption'];
757
            } elseif ($getSort) {
758
                $aColumn['caption'] = '<a href="'
759
                                      . $current_url
760
                                      . '?'
761
                                      . $this->_objectHandler->_itemname
762
                                      . '_'
763
                                      . 'sortsel='
764
                                      . $column->getKeyName()
765
                                      . '&'
766
                                      . $this->_objectHandler->_itemname
767
                                      . '_'
768
                                      . 'ordersel='
769
                                      . $orderArray[$order]['neworder']
770
                                      . $qs_param
771
                                      . '&'
772
                                      . $new_query_string
773
                                      . '">'
774
                                      . $aColumn['caption']
775
                                      . ' <img src="'
776
                                      . SMARTOBJECT_IMAGES_ACTIONS_URL
777
                                      . $orderArray[$order]['image']
778
                                      . '" alt="ASC"></a>';
779
            } else {
780
                $aColumn['caption'] = '<a href="' . $current_url . '?' . $this->_objectHandler->_itemname . '_' . 'sortsel=' . $column->getKeyName() . '&' . $this->_objectHandler->_itemname . '_' . 'ordersel=ASC' . $qs_param . '&' . $new_query_string . '">' . $aColumn['caption'] . '</a>';
781
            }
782
            $aColumns[] = $aColumn;
783
        }
784
        $this->_tpl->assign('smartobject_columns', $aColumns);
785
786
        if ($this->_quickSearch) {
787
            $this->_tpl->assign('smartobject_quicksearch', $this->_quickSearch['caption']);
788
        }
789
790
        $this->createTableRows();
791
792
        $this->_tpl->assign('smartobject_showFilterAndLimit', $this->_showFilterAndLimit);
793
        $this->_tpl->assign('smartobject_isTree', $this->_isTree);
794
        $this->_tpl->assign('smartobject_show_action_column_title', $this->_showActionsColumnTitle);
795
        $this->_tpl->assign('smartobject_table_header', $this->_tableHeader);
796
        $this->_tpl->assign('smartobject_table_footer', $this->_tableFooter);
797
        $this->_tpl->assign('smartobject_printer_friendly_page', $this->_printerFriendlyPage);
798
        $this->_tpl->assign('smartobject_user_side', $this->_userSide);
799
        $this->_tpl->assign('smartobject_has_actions', $this->_hasActions);
800
        $this->_tpl->assign('smartobject_head_css_class', $this->_head_css_class);
801
        $this->_tpl->assign('smartobject_actionButtons', $this->_actionButtons);
802
        $this->_tpl->assign('smartobject_introButtons', $this->_introButtons);
803
        $this->_tpl->assign('smartobject_id', $this->_id);
804
        if (!empty($this->_withSelectedActions)) {
805
            $this->_tpl->assign('smartobject_withSelectedActions', $this->_withSelectedActions);
806
        }
807
808
        $smartobjectTable_template = $this->_customTemplate ?: 'smartobject_smarttable_display.tpl';
809
        if ($fetchOnly) {
810
            return $this->_tpl->fetch('db:' . $smartobjectTable_template);
811
        } else {
812
            $this->_tpl->display('db:' . $smartobjectTable_template);
813
        }
814
    }
815
816
    public function disableColumnsSorting()
817
    {
818
        $this->_enableColumnsSorting = false;
819
    }
820
821
    /**
822
     * @param  bool $debug
823
     * @return mixed|string|void
824
     */
825
    public function fetch($debug = false)
826
    {
827
        return $this->render(true, $debug);
828
    }
829
}
830