Completed
Push — develop ( 053968...47dc8d )
by Maxim
12s
created

MakeTable::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 20
nc 1
nop 0
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * A utility class for presenting a provided array as a table view.  Includes
5
 * support for pagination, sorting by any column, providing optional header arrays,
6
 * providing classes for styling the table, rows, and cells (including alternate
7
 * row styling), as well as adding form controls to each row.
8
 *
9
 * @author Jason Coward <[email protected]> (MODX)
10
 */
11
class MakeTable
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...
12
{
13
    /**
14
     * @var string
15
     */
16
    public $actionField = '';
17
    /**
18
     * @var string
19
     */
20
    public $cellAction = '';
21
    /**
22
     * @var string
23
     */
24
    public $linkAction = '';
25
    /**
26
     * @var int
27
     */
28
    public $tableWidth = 0;
29
    /**
30
     * @var string
31
     */
32
    public $tableClass = '';
33
    /**
34
     * @var
35
     */
36
    public $tableID;
37
    /**
38
     * @var
39
     */
40
    public $thClass;
41
    /**
42
     * @var string
43
     */
44
    public $rowHeaderClass = '';
45
    /**
46
     * @var string
47
     */
48
    public $columnHeaderClass = '';
49
    /**
50
     * @var string
51
     */
52
    public $rowRegularClass = '';
53
    /**
54
     * @var string
55
     */
56
    public $rowAlternateClass = 'alt';
57
    /**
58
     * @var string
59
     */
60
    public $formName = 'tableForm';
61
    /**
62
     * @var string
63
     */
64
    public $formAction = '[~[*id*]~]';
65
    /**
66
     * @var string
67
     */
68
    public $formElementType = '';
69
    /**
70
     * @var string
71
     */
72
    public $formElementName = '';
73
    /**
74
     * @var string
75
     */
76
    public $rowAlternatingScheme = 'EVEN';
77
    /**
78
     * @var array
79
     */
80
    public $excludeFields = array();
81
    /**
82
     * @var int
83
     */
84
    public $allOption = 0;
85
    /**
86
     * @var
87
     */
88
    public $pageNav;
89
    /**
90
     * @var array
91
     */
92
    public $columnWidths = array();
93
    /**
94
     * @var array
95
     */
96
    public $selectedValues = array();
97
    /**
98
     * @var array
99
     */
100
    public $fieldHeaders = array();
101
    /**
102
     * @var string
103
     */
104
    public $extra = '';
105
106
    /**
107
     * Sets the default link href for all cells in the table.
108
     *
109
     * @param string $value A URL to execute when table cells are clicked.
110
     */
111
    public function setCellAction($value)
112
    {
113
        $this->cellAction = $this->prepareLink($value);
114
    }
115
116
    /**
117
     * Sets the default link href for the text presented in a cell.
118
     *
119
     * @param string $value A URL to execute when text within table cells are clicked.
120
     */
121
    public function setLinkAction($value)
122
    {
123
        $this->linkAction = $this->prepareLink($value);
124
    }
125
126
    /**
127
     * Sets the width attribute of the main HTML TABLE.
128
     *
129
     * @param int $value A valid width attribute for the HTML TABLE tag
130
     */
131
    public function setTableWidth($value)
132
    {
133
        $this->tableWidth = (int)$value;
134
    }
135
136
    /**
137
     * Sets the class attribute of the main HTML TABLE.
138
     *
139
     * @param string $value A class for the main HTML TABLE.
140
     */
141
    public function setTableClass($value)
142
    {
143
        $this->tableClass = $value;
144
    }
145
146
    /**
147
     * Sets the id attribute of the main HTML TABLE.
148
     *
149
     * @param string $value A class for the main HTML TABLE.
150
     */
151
    public function setTableID($value)
152
    {
153
        $this->tableID = $value;
154
    }
155
156
    /**
157
     * Sets the class attribute of the table header row.
158
     *
159
     * @param string $value A class for the table header row.
160
     */
161
    public function setRowHeaderClass($value)
162
    {
163
        $this->rowHeaderClass = $value;
164
    }
165
166
    /**
167
     * Sets the class attribute of the table header row.
168
     *
169
     * @param string $value A class for the table header row.
170
     */
171
    public function setThHeaderClass($value)
172
    {
173
        $this->thClass = $value;
174
    }
175
176
    /**
177
     * Sets the class attribute of the column header row.
178
     *
179
     * @param string $value A class for the column header row.
180
     */
181
    public function setColumnHeaderClass($value)
182
    {
183
        $this->columnHeaderClass = $value;
184
    }
185
186
    /**
187
     * Sets the class attribute of regular table rows.
188
     *
189
     * @param string $value A class for regular table rows.
190
     */
191
    public function setRowRegularClass($value)
192
    {
193
        $this->rowRegularClass = $value;
194
    }
195
196
    /**
197
     * Sets the class attribute of alternate table rows.
198
     *
199
     * @param string $value A class for alternate table rows.
200
     */
201
    public function setRowAlternateClass($value)
202
    {
203
        $this->rowAlternateClass = $value;
204
    }
205
206
    /**
207
     * Sets the type of INPUT form element to be presented as the first column.
208
     *
209
     * @param string $value Indicates the INPUT form element type attribute.
210
     */
211
    public function setFormElementType($value)
212
    {
213
        $this->formElementType = $value;
214
    }
215
216
    /**
217
     * Sets the name of the INPUT form element to be presented as the first column.
218
     *
219
     * @param string $value Indicates the INPUT form element name attribute.
220
     */
221
    public function setFormElementName($value)
222
    {
223
        $this->formElementName = $value;
224
    }
225
226
    /**
227
     * Sets the name of the FORM to wrap the table in when a form element has
228
     * been indicated.
229
     *
230
     * @param string $value Indicates the FORM name attribute.
231
     */
232
    public function setFormName($value)
233
    {
234
        $this->formName = $value;
235
    }
236
237
    /**
238
     * Sets the action of the FORM element.
239
     *
240
     * @param string $value Indicates the FORM action attribute.
241
     */
242
    public function setFormAction($value)
243
    {
244
        $this->formAction = $value;
245
    }
246
247
    /**
248
     * Excludes fields from the table by array key.
249
     *
250
     * @param array $value An Array of field keys to exclude from the table.
251
     */
252
    public function setExcludeFields($value)
253
    {
254
        $this->excludeFields = $value;
255
    }
256
257
    /**
258
     * Sets the table to provide alternate row colors using ODD or EVEN rows
259
     *
260
     * @param string $value 'ODD' or 'EVEN' to indicate the alternate row scheme.
261
     */
262
    public function setRowAlternatingScheme($value)
263
    {
264
        $this->rowAlternatingScheme = $value;
265
    }
266
267
    /**
268
     * Sets the default field value to be used when appending query parameters
269
     * to link actions.
270
     *
271
     * @param string $value The key of the field to add as a query string parameter.
272
     */
273
    public function setActionFieldName($value)
274
    {
275
        $this->actionField = $value;
276
    }
277
278
    /**
279
     * Sets the width attribute of each column in the array.
280
     *
281
     * @param array $value An Array of column widths in the order of the keys in the
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
282
     *            source table array.
283
     */
284
    public function setColumnWidths($widthArray)
285
    {
286
        $this->columnWidths = $widthArray;
287
    }
288
289
    /**
290
     * An optional array of values that can be preselected when using
291
     *
292
     * @param array $value Indicates the INPUT form element type attribute.
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
293
     */
294
    public function setSelectedValues($valueArray)
295
    {
296
        $this->selectedValues = $valueArray;
297
    }
298
299
    /**
300
     * Sets extra content to be presented following the table (but within
301
     * the form, if a form is being rendered with the table).
302
     *
303
     * @param string $value A string of additional content.
304
     */
305
    public function setExtra($value)
306
    {
307
        $this->extra = $value;
308
    }
309
310
    /**
311
     * Retrieves the width of a specific table column by index position.
312
     *
313
     * @param int $columnPosition The index of the column to get the width for.
314
     * @return string
315
     */
316
    public function getColumnWidth($columnPosition)
317
    {
318
        $currentWidth = '';
319
        if (is_array($this->columnWidths)) {
320
            $currentWidth = $this->columnWidths[$columnPosition] ? ' width="' . $this->columnWidths[$columnPosition] . '" ' : '';
321
        }
322
323
        return $currentWidth;
324
    }
325
326
    /**
327
     * Determines what class the current row should have applied.
328
     *
329
     * @param int $value The position of the current row being rendered.
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
330
     * @return string
331
     */
332
    public function determineRowClass($position)
333
    {
334
        switch ($this->rowAlternatingScheme) {
335
            case 'ODD' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
336
                $modRemainder = 1;
337
                break;
338
            case 'EVEN' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
339
            default:
340
                $modRemainder = 0;
341
                break;
342
        }
343
        if ($position % 2 == $modRemainder) {
344
            $currentClass = $this->rowRegularClass;
345
        } else {
346
            $currentClass = $this->rowAlternateClass;
347
        }
348
349
        return ' class="' . $currentClass . '"';
350
    }
351
352
    /**
353
     * Generates an onclick action applied to the current cell, to execute
354
     * any specified cell actions.
355
     *
356
     * @param string $value Indicates the INPUT form element type attribute.
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
357
     * @return string
358
     */
359 View Code Duplication
    public function getCellAction($currentActionFieldValue)
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...
360
    {
361
        $cellAction = '';
362
        if ($this->cellAction) {
363
            $cellAction = ' onClick="javascript:window.location=\'' . $this->cellAction . $this->actionField . '=' . urlencode($currentActionFieldValue) . '\'" ';
364
        }
365
366
        return $cellAction;
367
    }
368
369
    /**
370
     * Generates the cell content, including any specified action fields values.
371
     *
372
     * @param string $currentActionFieldValue The value to be applied to the link action.
373
     * @param string $value The value of the cell.
374
     * @return string
375
     */
376 View Code Duplication
    public function createCellText($currentActionFieldValue, $value)
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...
377
    {
378
        $cell = $value;
379
        if ($this->linkAction) {
380
            $cell = '<a href="' . $this->linkAction . $this->actionField . '=' . urlencode($currentActionFieldValue) . '">' . $cell . '</a>';
381
        }
382
383
        return $cell;
384
    }
385
386
    /**
387
     * Sets an option to generate a check all link when checkbox is indicated
388
     * as the table formElementType.
389
     */
390
    public function setAllOption()
391
    {
392
        $this->allOption = 1;
393
    }
394
395
    /**
396
     * Function to prepare a link generated in the table cell/link actions.
397
     *
398
     * @param string $value Indicates the INPUT form element type attribute.
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
399
     * @return string
400
     */
401
    public function prepareLink($link)
402
    {
403
        if (strstr($link, '?')) {
404
            $end = '&';
405
        } else {
406
            $end = '?';
407
        }
408
409
        return $link . $end;
410
    }
411
412
    /**
413
     * Generates the table content.
414
     *
415
     * @param array $fieldsArray The associative array representing the table rows
416
     * and columns.
417
     * @param array $fieldHeadersArray An optional array of values for providing
418
     * alternative field headers; this is an associative arrays of keys from
419
     * the $fieldsArray where the values represent the alt heading content
420
     * for each column.
421
     * @return string
422
     */
423
    public function create($fieldsArray, $fieldHeadersArray = array(), $linkpage = "")
0 ignored issues
show
Unused Code introduced by
The parameter $linkpage 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...
424
    {
425
        global $_lang;
426
        if (is_array($fieldsArray)) {
427
            $i = 0;
428
            foreach ($fieldsArray as $fieldName => $fieldValue) {
429
                $table .= "\t<tr" . $this->determineRowClass($i) . ">\n";
0 ignored issues
show
Bug introduced by
The variable $table 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...
430
                $currentActionFieldValue = $fieldValue[$this->actionField];
431
                if (is_array($this->selectedValues)) {
432
                    $isChecked = array_search($currentActionFieldValue, $this->selectedValues) === false ? 0 : 1;
433
                } else {
434
                    $isChecked = false;
435
                }
436
                $table .= $this->addFormField($currentActionFieldValue, $isChecked);
0 ignored issues
show
Bug introduced by
It seems like $isChecked defined by array_search($currentAct...lues) === false ? 0 : 1 on line 432 can also be of type integer; however, MakeTable::addFormField() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
437
                $colPosition = 0;
438
                foreach ($fieldValue as $key => $value) {
439
                    if (!in_array($key, $this->excludeFields)) {
440
                        $table .= "\t\t<td" . $this->getCellAction($currentActionFieldValue) . ">";
441
                        $table .= $this->createCellText($currentActionFieldValue, $value);
442
                        $table .= "</td>\n";
443
                        if ($i == 0) {
444
                            if (empty ($header) && $this->formElementType) {
445
                                $header .= "\t\t<th style=\"width:32px\" " . ($this->thClass ? 'class="' . $this->thClass . '"' : '') . ">" . ($this->allOption ? '<a href="javascript:clickAll()">all</a>' : '') . "</th>\n";
0 ignored issues
show
Bug introduced by
The variable $header 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...
446
                            }
447
                            $headerText = array_key_exists($key, $fieldHeadersArray) ? $fieldHeadersArray[$key] : $key;
448
                            $header .= "\t\t<th" . $this->getColumnWidth($colPosition) . ($this->thClass ? ' class="' . $this->thClass . '" ' : '') . ">" . $headerText . "</th>\n";
449
                        }
450
                        $colPosition++;
451
                    }
452
                }
453
                $i++;
454
                $table .= "\t</tr>\n";
455
            }
456
            $table = "\n" . '<table' . ($this->tableWidth > 0 ? ' width="' . $this->tableWidth . '"' : '') . ($this->tableClass ? ' class="' . $this->tableClass . '"' : '') . ($this->tableID ? ' id="' . $this->tableID . '"' : '') . ">\n" . ($header ? "\t<thead>\n\t<tr class=\"" . $this->rowHeaderClass . "\">\n" . $header . "\t</tr>\n\t</thead>\n" : '') . $table . "</table>\n";
457
            if ($this->formElementType) {
458
                $table = "\n" . '<form id="' . $this->formName . '" name="' . $this->formName . '" action="' . $this->formAction . '" method="POST">' . $table;
459
            }
460
            if (strlen($this->pageNav) > 1) {//changed to display the pagination if exists.
461
                /* commented this part because of cookie
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
462
                $table .= '<div id="max-display-records" ><select style="display:inline" onchange="javascript:updatePageSize(this[this.selectedIndex].value);">';
463
                $pageSizes= array (10, 25, 50, 100, 250);
464
                for ($i= 0; $i < count($pageSizes); $i ++) {
465
                    $table .= '<option value="'.$pageSizes[$i].'"';
466
                    $table .= MAX_DISPLAY_RECORDS_NUM == $pageSizes[$i] ? ' selected ' : '';
467
                    $table .= '>'.$pageSizes[$i].'</option>';
468
                }
469
470
                $table .= '</select>'.$_lang["pagination_table_perpage"].'</div>';
471
                */
472
                $table .= '<div id="pagination" class="paginate">' . $_lang["pagination_table_gotopage"] . '<ul>' . $this->pageNav . '</ul></div>';
473
                //$table .= '<script language="javascript">function updatePageSize(size){window.location = \''.$this->prepareLink($linkpage).'pageSize=\'+size;}</script>';
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
474
475
            }
476
            if ($this->allOption) {
477
                $table .= '
478
<script language="javascript">
479
	toggled = 0;
480
	function clickAll() {
481
		myform = document.getElementById("' . $this->formName . '");
482
		for(i=0;i<myform.length;i++) {
483
			if(myform.elements[i].type==\'checkbox\') {
484
				myform.elements[i].checked=(toggled?false:true);
485
			}
486
		}
487
		toggled = (toggled?0:1);
488
	}
489
</script>';
490
            }
491
            if ($this->formElementType) {
492
                if ($this->extra) {
493
                    $table .= "\n" . $this->extra . "\n";
494
                }
495
                $table .= "\n" . '</form>' . "\n";
496
            }
497
498
            return $table;
499
        }
500
501
        return '';
502
    }
503
504
    /**
505
     * Generates optional paging navigation controls for the table.
506
     *
507
     * @param int $numRecords The number of records to show per page.
508
     * @param string $qs An optional query string to be appended to the paging links
509
     * @return void
510
     */
511
    public function createPagingNavigation($numRecords, $qs = '')
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $qs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
createPagingNavigation uses the super-global variable $_GET 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...
512
    {
513
        global $_lang;
514
        $currentPage = (is_numeric($_GET['page']) ? $_GET['page'] : 1);
515
        $numPages = ceil($numRecords / MAX_DISPLAY_RECORDS_NUM);
516
        $nav = '';
517
        if ($numPages > 1) {
518
            $currentURL = empty($qs) ? '' : '?' . $qs;
519
            if ($currentPage > 6) {
520
                $nav .= $this->createPageLink($currentURL, 1, $_lang["pagination_table_first"]);
521
            }
522
            if ($currentPage != 1) {
523
                $nav .= $this->createPageLink($currentURL, $currentPage - 1, '&lt;&lt;');
524
            }
525
            $offset = -4 + ($currentPage < 5 ? (5 - $currentPage) : 0);
526
            $i = 1;
527
            while ($i < 10 && ($currentPage + $offset <= $numPages)) {
528
                if ($currentPage == $currentPage + $offset) {
529
                    $nav .= $this->createPageLink($currentURL, $currentPage + $offset, $currentPage + $offset, true);
530
                } else {
531
                    $nav .= $this->createPageLink($currentURL, $currentPage + $offset, $currentPage + $offset);
532
                }
533
                $i++;
534
                $offset++;
535
            }
536
            if ($currentPage < $numPages) {
537
                $nav .= $this->createPageLink($currentURL, $currentPage + 1, '&gt;&gt;');
538
            }
539
            if ($currentPage != $numPages) {
540
                $nav .= $this->createPageLink($currentURL, $numPages, $_lang["pagination_table_last"]);
541
            }
542
        }
543
        $this->pageNav = ' ' . $nav;
544
    }
545
546
    /**
547
     * Creates an individual page link for the paging navigation.
548
     *
549
     * @param string $link The link for the page, defaulted to the current document.
550
     * @param int $pageNum The page number of the link.
551
     * @param string $displayText The text of the link.
552
     * @param bool $currentPage Indicates if the link is to the current page.
553
     * @param string $qs And optional query string to be appended to the link.
554
     * @return string
555
     */
556
    public function createPageLink($link = '', $pageNum, $displayText, $currentPage = false, $qs = '')
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $qs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
createPageLink uses the super-global variable $_GET 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...
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
557
    {
558
        global $modx;
559
        $orderBy = !empty($_GET['orderby']) ? '&orderby=' . $_GET['orderby'] : '';
560
        $orderDir = !empty($_GET['orderdir']) ? '&orderdir=' . $_GET['orderdir'] : '';
561
        if (!empty($qs)) {
562
            $qs = "?$qs";
563
        }
564
        $link = empty($link) ? $modx->makeUrl($modx->documentIdentifier, $modx->documentObject['alias'],
565
            $qs . "page=$pageNum$orderBy$orderDir") : $this->prepareLink($link) . "page=$pageNum";
566
        $nav = '<li' . ($currentPage ? ' class="currentPage"' : '') . '><a' . ($currentPage ? ' class="currentPage"' : '') . ' href="' . $link . '">' . $displayText . '</a></li>' . "\n";
567
568
        return $nav;
569
    }
570
571
    /**
572
     * Adds an INPUT form element column to the table.
573
     *
574
     * @param string $value The value attribute of the element.
575
     * @param bool $isChecked Indicates if the checked attribute should apply to the
576
     * element.
577
     * @return string
578
     */
579
    public function addFormField($value, $isChecked)
580
    {
581
        $field = '';
582
        if ($this->formElementType) {
583
            $checked = $isChecked ? "checked " : "";
584
            $field = "\t\t" . '<td><input type="' . $this->formElementType . '" name="' . ($this->formElementName ? $this->formElementName : $value) . '"  value="' . $value . '" ' . $checked . '/></td>' . "\n";
585
        }
586
587
        return $field;
588
    }
589
590
    /**
591
     * Generates the proper LIMIT clause for queries to retrieve paged results in
592
     * a MakeTable $fieldsArray.
593
     * @return string
594
     */
595
    public function handlePaging()
0 ignored issues
show
Coding Style introduced by
handlePaging uses the super-global variable $_GET 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...
596
    {
597
        $offset = (is_numeric($_GET['page']) && $_GET['page'] > 0) ? $_GET['page'] - 1 : 0;
598
        $limitClause = ' LIMIT ' . ($offset * MAX_DISPLAY_RECORDS_NUM) . ', ' . MAX_DISPLAY_RECORDS_NUM;
599
600
        return $limitClause;
601
    }
602
603
    /**
604
     * Generates the SORT BY clause for queries used to retrieve a MakeTable
605
     * $fieldsArray
606
     *
607
     * @param bool $natural_order If true, the results are returned in natural order.
608
     * @return string
609
     */
610
    public function handleSorting($natural_order = false)
0 ignored issues
show
Coding Style introduced by
handleSorting uses the super-global variable $_GET 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...
Coding Style Naming introduced by
The parameter $natural_order is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
611
    {
612
        $orderByClause = '';
613
        if ((bool)$natural_order === false) {
614
            $orderby = !empty($_GET['orderby']) ? $_GET['orderby'] : "id";
615
            $orderdir = !empty($_GET['orderdir']) ? $_GET['orderdir'] : "DESC";
616
            $orderByClause = !empty($orderby) ? ' ORDER BY ' . $orderby . ' ' . $orderdir . ' ' : "";
617
        }
618
619
        return $orderByClause;
620
    }
621
622
    /**
623
     * Generates a link to order by a specific $fieldsArray key; use to generate
624
     * sort by links in the MakeTable $fieldHeadingsArray values.
625
     *
626
     * @param string $key The $fieldsArray key for the column to sort by.
627
     * @param string $text The text for the link (e.g. table column header).
628
     * @param string $qs An optional query string to append to the order by link.
629
     * @return string
630
     */
631
    public function prepareOrderByLink($key, $text, $qs = '')
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $qs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
prepareOrderByLink uses the super-global variable $_GET 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...
632
    {
633
        global $modx;
634
        if (!empty($_GET['orderdir'])) {
635
            $orderDir = strtolower($_GET['orderdir']) == 'desc' ? '&orderdir=asc' : '&orderdir=desc';
636
        } else {
637
            $orderDir = '&orderdir=asc';
638
        }
639
        if (!empty($qs)) {
640
            if (!strrpos($qs, '&') == strlen($qs) - 1) {
641
                $qs .= '&';
642
            }
643
        }
644
645
        return '<a href="[~' . $modx->documentIdentifier . '~]?' . $qs . 'orderby=' . $key . $orderDir . '">' . $text . '</a>';
646
    }
647
648
}
649