Completed
Push — master ( 1fc5ed...1a572b )
by Konstantinos
03:56
created

QueryBuilder::createQueryOrder()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3
Metric Value
dl 0
loc 18
rs 9.4285
ccs 9
cts 9
cp 1
cc 3
eloc 11
nc 3
nop 0
crap 3
1
<?php
2
/**
3
 * This file contains a class to quickly generate database queries for models
4
 *
5
 * @package    BZiON\Models\QueryBuilder
6
 * @license    https://github.com/allejo/bzion/blob/master/LICENSE.md GNU General Public License Version 3
7
 */
8
9
/**
10
 * This class can be used to search for models with specific characteristics in
11
 * the database.
12
 *
13
 * Note that most methods of this class return itself, so that you can easily
14
 * add a number of different filters.
15
 *
16
 * <code>
17
 *     return Team::getQueryBuilder()
18
 *     ->active()
19
 *     ->where('name')->startsWith('a')
20
 *     ->sortBy('name')->reverse()
21
 *     ->getModels();
22
 * </code>
23
 *
24
 * @package    BZiON\Models\QueryBuilder
25
 */
26
class QueryBuilder implements Countable
27
{
28
    /**
29
     * The type of the model we're building a query for
30
     * @var string
31
     */
32
    protected $type;
33
34
    /**
35
     * The columns that the model provided us
36
     * @var array
37
     */
38
    protected $columns = array('id' => 'id');
39
40
    /**
41
     * The conditions to include in WHERE
42
     * @var string[]
43
     */
44
    protected $conditions = array();
45
46
    /**
47
     * The MySQL value parameters
48
     * @var array
49
     */
50
    protected $parameters = array();
51
52
    /**
53
     * The MySQL parameter types
54
     * @var string
55
     */
56
    protected $types = '';
57
58
    /**
59
     * The MySQL value parameters for pagination
60
     * @var array
61
     */
62
    protected $paginationParameters = array();
63
64
    /**
65
     * The MySQL parameter types for pagination
66
     * @var string
67
     */
68
    protected $paginationTypes = '';
69
70
    /**
71
     * Extra MySQL query string to pass
72
     * @var string
73
     */
74
    protected $extras = '';
75
76
    /**
77
     * Extra MySQL query groupby string to pass
78
     * @var string
79
     */
80
    protected $groupQuery = '';
81
82
    /**
83
     * A column based on which we should sort the results
84
     * @var string|null
85
     */
86
    private $sortBy = null;
87
88
    /**
89
     * Whether to reverse the results
90
     * @var bool
91
     */
92
    private $reverseSort = false;
93
94
    /**
95
     * The currently selected column
96
     * @var string|null
97
     */
98
    private $currentColumn = null;
99
100
    /**
101
     * The currently selected column without the table name (unless it was
102
     * explicitly provided)
103
     * @var string|null
104
     */
105
    protected $currentColumnRaw = null;
106
107
    /**
108
     * A column to consider the name of the model
109
     * @var string|null
110
     */
111
    private $nameColumn = null;
112
113
    /**
114
     * Whether to return the results as arrays instead of models
115
     * @var bool
116
     */
117
    private $returnArray = false;
0 ignored issues
show
Unused Code introduced by
The property $returnArray is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
118
119
    /**
120
     * The page to return
121
     * @var int|null
122
     */
123
    private $page = null;
124
125
    /**
126
     * Whether the ID of the first/last element has been provided
127
     * @var bool
128
     */
129
    private $limited = false;
130
131
    /**
132
     * The number of elements on every page
133
     * @var int
134
     */
135
    protected $resultsPerPage = 30;
136
137
    /**
138
     * Create a new QueryBuilder
139
     *
140
     * A new query builder should be created on a static getQueryBuilder()
141
     * method on each model. The options array can contain the following
142
     * properties:
143
     *
144
     * - `columns`: An associative array - the key of each entry is the column
145
     *   name that will be used by other methods, while the value is
146
     *   is the column name that is used in the database structure
147
     *
148
     * - `activeStatuses`: If the model has a status column, this should be
149
     *                     a list of values that make the entry be considered
150
     *                     "active"
151
     *
152
     * - `name`: The name of the column which represents the name of the object
153
     *
154
     * @param string $type    The type of the Model (e.g. "Player" or "Match")
155
     * @param array  $options The options to pass to the builder (see above)
156
     */
157 1
    public function __construct($type, $options = array())
158
    {
159 1
        $this->type = $type;
160
161 1
        if (isset($options['columns'])) {
162 1
            $this->columns += $options['columns'];
163
        }
164
165 1
        if (isset($options['name'])) {
166 1
            $this->nameColumn = $options['name'];
167
        }
168 1
    }
169
170
    /**
171
     * Select a column
172
     *
173
     * `$queryBuilder->where('username')->equals('administrator');`
174
     *
175
     * @param  string $column The column to select
176
     * @return self
177
     */
178 1
    public function where($column)
179
    {
180 1
        if (!isset($this->columns[$column])) {
181
            throw new InvalidArgumentException("Unknown column '$column'");
182
        }
183
184 1
        $this->column($this->columns[$column]);
185
186 1
        return $this;
187
    }
188
189
    /**
190
     * Request that a column equals a string (case-insensitive)
191
     *
192
     * @param  string $string The string that the column's value should equal to
193
     * @return self
194
     */
195
    public function equals($string)
196
    {
197
        $this->addColumnCondition("= ?", $string, 's');
198
199
        return $this;
200
    }
201
202
    /**
203
     * Request that a column doesNOT equals a string (case-insensitive)
204
     *
205
     * @param  string $string The string that the column's value should equal to
206
     * @return self
207
     */
208 1
    public function notEquals($string)
209
    {
210 1
        $this->addColumnCondition("!= ?", $string, 's');
211
212 1
        return $this;
213
    }
214
215
    /**
216
     * Request that a column is greater than a quantity
217
     *
218
     * @param  string $quantity The quantity to test against
219
     * @return self
220
     */
221
    public function greaterThan($quantity)
222
    {
223
        $this->addColumnCondition("> ?", $quantity, 's');
224
225
        return $this;
226
    }
227
228
    /**
229
     * Request that a column is less than a quantity
230
     *
231
     * @param  string $quantity The quantity to test against
232
     * @return self
233
     */
234
    public function lessThan($quantity)
235
    {
236
        $this->addColumnCondition("< ?", $quantity, 's');
237
238
        return $this;
239
    }
240
241
    /**
242
     * Request that a timestamp is before the specified time
243
     *
244
     * @param string|TimeDate $time      The timestamp to compare to
245
     * @param bool            $inclusive Whether to include the given timestamp
246
     * @param bool            $reverse   Whether to reverse the results
247
     */
248
    public function isBefore($time, $inclusive = false, $reverse = false)
249
    {
250
        return $this->isAfter($time, $inclusive, !$reverse);
251
    }
252
253
    /**
254
     * Request that a timestamp is after the specified time
255
     *
256
     * @param string|TimeDate $time      The timestamp to compare to
257
     * @param bool            $inclusive Whether to include the given timestamp
258
     * @param bool            $reverse   Whether to reverse the results
259
     */
260 1
    public function isAfter($time, $inclusive = false, $reverse = false)
261
    {
262 1
        if ($time instanceof TimeDate) {
263 1
            $time = $time->toMysql();
264
        }
265
266 1
        $comparison  = ($reverse)   ? '<' : '>';
267 1
        $comparison .= ($inclusive) ? '=' : '';
268
269 1
        $this->addColumnCondition("$comparison ?",  $time, 's');
270
271 1
        return $this;
272
    }
273
274
    /**
275
     * Request that a column equals a number
276
     *
277
     * @param  int|Model|null $number The number that the column's value should
278
     *                                equal to. If a Model is provided, use the
279
     *                                model's ID, while null values are ignored.
280
     * @return self
281
     */
282 1 View Code Duplication
    public function is($number)
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...
283
    {
284 1
        if ($number === null) {
285
            return $this;
286
        }
287
288 1
        if ($number instanceof Model) {
289 1
            $number = $number->getId();
290
        }
291
292 1
        $this->addColumnCondition("= ?", $number, 'i');
293
294 1
        return $this;
295
    }
296
297
    /**
298
     * Request that a column equals one of some strings
299
     *
300
     * @param  string[] $strings The list of accepted values for the column
301
     * @return self
302
     */
303 1
    public function isOneOf($strings)
304
    {
305 1
        $count = count($strings);
306 1
        $types = str_repeat('s', $count);
307 1
        $questionMarks = str_repeat(',?', $count);
308
309
        // Remove first comma from questionMarks so that MySQL can read our query
310 1
        $questionMarks = ltrim($questionMarks, ',');
311
312 1
        $this->addColumnCondition("IN ($questionMarks)", $strings, $types);
313
314 1
        return $this;
315
    }
316
317
    /**
318
     * Request that a column value starts with a string (case-insensitive)
319
     *
320
     * @param  string $string The substring that the column's value should start with
321
     * @return self
322
     */
323
    public function startsWith($string)
324
    {
325
        $this->addColumnCondition("LIKE CONCAT(?, '%')", $string, 's');
326
327
        return $this;
328
    }
329
330
    /**
331
     * Request that a specific model is not returned
332
     *
333
     * @param  Model|int $model The ID or model you don't want to get
334
     * @return self
335
     */
336 View Code Duplication
    public function except($model)
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...
337
    {
338
        if ($model instanceof Model) {
339
            $model = $model->getId();
340
        }
341
342
        $this->where('id');
343
        $this->addColumnCondition("!= ?", $model, 'i');
344
345
        return $this;
346
    }
347
348
    /**
349
     * Return the results sorted by the value of a column
350
     *
351
     * @param  string $column The column based on which the results should be ordered
352
     * @return self
353
     */
354 1
    public function sortBy($column)
355
    {
356 1
        if (!isset($this->columns[$column])) {
357
            throw new Exception("Unknown column");
358
        }
359
360 1
        $this->sortBy = $this->columns[$column];
361
362 1
        return $this;
363
    }
364
365
    /**
366
     * Reverse the order
367
     *
368
     * Note: This only works if you have specified a column in the sortBy() method
369
     *
370
     * @return self
371
     */
372 1
    public function reverse()
373
    {
374 1
        $this->reverseSort = !$this->reverseSort;
375
376 1
        return $this;
377
    }
378
379
    /**
380
     * Specify the number of results per page
381
     *
382
     * @param  int  $count The number of results
383
     * @return self
384
     */
385 1
    public function limit($count)
386
    {
387 1
        $this->resultsPerPage = $count;
388
389 1
        return $this;
390
    }
391
392
    /**
393
     * Only show results from a specific page
394
     *
395
     * @param  int|null $page The page number (or null to show all pages - counting starts from 0)
396
     * @return self
397
     */
398 1
    public function fromPage($page)
399
    {
400 1
        $this->page = $page;
401
402 1
        return $this;
403
    }
404
405
    /**
406
     * End with a specific result
407
     *
408
     * @param  int|Model $model     The model (or database ID) after the first result
409
     * @param  bool   $inclusive Whether to include the provided model
410
     * @param  bool   $reverse   Whether to reverse the results
411
     * @return self
412
     */
413 1
    public function endAt($model, $inclusive = false, $reverse = false)
414
    {
415 1
        return $this->startAt($model, $inclusive, !$reverse);
416
    }
417
418
    /**
419
     * Start with a specific result
420
     *
421
     * @param  int|Model $model     The model (or database ID) before the first result
422
     * @param  bool   $inclusive Whether to include the provided model
423
     * @param  bool   $reverse   Whether to reverse the results
424
     * @return self
425
     */
426 1
    public function startAt($model, $inclusive = false, $reverse = false)
427
    {
428 1
        if (!$model) {
429 1
            return $this;
430
        } elseif ($model instanceof Model && !$model->isValid()) {
431
            return $this;
432
        }
433
434
        $this->column($this->sortBy);
435
        $this->limited = true;
436
        $column = $this->currentColumn;
437
        $table  = $this->getTable();
438
439
        $comparison  = $this->reverseSort ^ $reverse;
440
        $comparison  = ($comparison) ? '>' : '<';
441
        $comparison .= ($inclusive)  ? '=' : '';
442
        $id = ($model instanceof Model) ? $model->getId() : $model;
443
444
        // Compare an element's timestamp to the timestamp of $model; if it's the
445
        // same, perform the comparison using IDs
446
        $this->addColumnCondition(
447
            "$comparison (SELECT $column FROM $table WHERE id = ?) OR ($column = (SELECT $column FROM $table WHERE id = ?) AND id $comparison ?)",
448
            array($id, $id, $id),
449
            'iii'
450
        );
451
452
        return $this;
453
    }
454
455
    /**
456
     * Request that only "active" Models should be returned
457
     *
458
     * @return self
459
     */
460 1
    public function active()
461
    {
462 1
        if (!isset($this->columns['status'])) {
463
            return $this;
464
        }
465
466 1
        $type = $this->type;
467
468 1
        return $this->where('status')->isOneOf($type::getActiveStatuses());
469
    }
470
471
    /**
472
     * Make sure that Models invisible to a player are not returned
473
     *
474
     * Note that this method does not take PermissionModel::canBeSeenBy() into
475
     * consideration for performance purposes, so you will have to override this
476
     * in your query builder if necessary.
477
     *
478
     * @param  Player  $player      The player in question
479
     * @param  bool $showDeleted false to hide deleted models even from admins
480
     * @return self
481
     */
482 1
    public function visibleTo($player, $showDeleted = false)
483
    {
484 1
        $type = $this->type;
485
486 1
        if (is_subclass_of($type, "PermissionModel")
487 1
         && $player->hasPermission($type::EDIT_PERMISSION)) {
488
            // The player is an admin who can see hidden models
489 1
            if ($showDeleted) {
490
                return $this;
491
            } else {
492 1
                return $this->where('status')->notEquals('deleted');
493
            }
494
        } else {
495 1
            return $this->active();
496
        }
497
    }
498
499
    /**
500
     * Perform the query and get back the results in an array of names
501
     *
502
     * @return string[] An array of the type $id => $name
503
     */
504 1
    public function getNames()
505
    {
506 1
        if (!$this->nameColumn) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->nameColumn of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
507
            throw new Exception("You haven't specified a name column");
508
        }
509
510 1
        $results = $this->getArray($this->nameColumn);
511
512 1
        return array_column($results, $this->nameColumn, 'id');
513
    }
514
515
    /**
516
     * Perform the query and get back the results in a list of arrays
517
     *
518
     * @todo   Play with partial models?
519
     * @param  string|string[] $columns The column(s) that should be returned
520
     * @return array[]
521
     */
522 1
    public function getArray($columns)
523
    {
524 1
        if (!is_array($columns)) {
525 1
            $columns = array($columns);
526
        }
527
528 1
        $db = Database::getInstance();
529
530 1
        return $db->query($this->createQuery($columns), $this->getTypes(), $this->getParameters());
531
    }
532
533
    /**
534
     * An alias for QueryBuilder::getModels(), with fast fetching on by default
535
     * and no return of results
536
     *
537
     * @param  bool $fastFetch Whether to perform one query to load all
538
     *                            the model data instead of fetching them
539
     *                            one by one
540
     * @return void
541
     */
542
    public function addToCache($fastFetch = true)
543
    {
544
        $this->getModels($fastFetch);
545
    }
546
547
    /**
548
     * Perform the query and get the results as Models
549
     *
550
     * @todo Fix fast fetch for queries with multiple tables
551
     * @param  bool $fastFetch Whether to perform one query to load all
552
     *                            the model data instead of fetching them
553
     *                            one by one (ignores cache)
554
     * @return array
555
     */
556 1
    public function getModels($fastFetch = false)
557
    {
558 1
        $db   = Database::getInstance();
559 1
        $type = $this->type;
560
561 1
        $columns = ($fastFetch) ? $type::getEagerColumns() : array();
562
563 1
        $results = $db->query($this->createQuery($columns), $this->getTypes(), $this->getParameters());
564
565 1
        if ($fastFetch) {
566 1
            return $type::createFromDatabaseResults($results);
567
        } else {
568 1
            return $type::arrayIdToModel(array_column($results, 'id'));
569
        }
570
    }
571
572
    /**
573
     * Count the results
574
     *
575
     * @return int
576
     */
577 1
    public function count()
578
    {
579 1
        $table  = $this->getTable();
580 1
        $params = $this->createQueryParams(false);
581 1
        $db     = Database::getInstance();
582 1
        $query  = "SELECT COUNT(*) FROM $table $params";
583
584
        // We don't want pagination to affect our results so don't use the functions that combine
585
        // pagination results
586 1
        $results = $db->query($query, $this->types, $this->parameters);
587
588 1
        return $results[0]['COUNT(*)'];
589
    }
590
591
    /**
592
     * Count the number of pages that all the models could be separated into
593
     */
594 1
    public function countPages()
595
    {
596 1
        return ceil($this->count() / $this->getResultsPerPage());
597
    }
598
599
    /**
600
     * Find if there is any result
601
     *
602
     * @return bool
603
     */
604 1
    public function any()
605
    {
606
        // Make sure that we don't mess with the user's options
607 1
        $query = clone $this;
608
609 1
        $query->limit(1);
610
611 1
        return $query->count() > 0;
612
    }
613
614
    /**
615
     * Get the amount of results that are returned per page
616
     * @return int
617
     */
618 1
    public function getResultsPerPage()
619
    {
620 1
        return $this->resultsPerPage;
621
    }
622
623
    /**
624
     * Select a column to perform opeations on
625
     *
626
     * This is identical to the `where()` method, except that the column is
627
     * specified as a MySQL column and not as a column name given by the model
628
     *
629
     * @param  string $column The column to select
630
     * @return self
631
     */
632 1
    protected function column($column)
633
    {
634 1
        if (strpos($column, '.') === false) {
635
            // Add the table name to the column if it isn't there already so that
636
            // MySQL knows what to do when handling multiple tables
637 1
            $table = $this->getTable();
638 1
            $this->currentColumn = "`$table`.`$column`";
639
        } else {
640 1
            $this->currentColumn = $column;
641
        }
642
643 1
        $this->currentColumnRaw = $column;
644
645 1
        return $this;
646
    }
647
648
    /**
649
     * Add a condition for the column
650
     * @param  string $condition The MySQL condition
651
     * @param  mixed  $value     Value(s) to pass to MySQL
652
     * @param  string $type      The type of the values
653
     * @return void
654
     */
655 1
    protected function addColumnCondition($condition, $value, $type)
656
    {
657 1
        if (!$this->currentColumn) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentColumn of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
658
            throw new Exception("You haven't selected a column!");
659
        }
660
661 1
        if (!is_array($value)) {
662 1
            $value = array($value);
663
        }
664
665 1
        $this->conditions[] = "{$this->currentColumn} $condition";
666 1
        $this->parameters   = array_merge($this->parameters, $value);
667 1
        $this->types       .= $type;
668
669 1
        $this->currentColumn = null;
670 1
        $this->currentColumnRaw = null;
671 1
    }
672
673
    /**
674
     * Get the MySQL extra parameters
675
     *
676
     * @param  bool $respectPagination Whether to respect pagination or not; useful for when pagination should be ignored such as count
677
     * @return string
678
     */
679 1
    protected function createQueryParams($respectPagination = true)
680
    {
681 1
        $extras     = $this->extras;
682 1
        $conditions = $this->createQueryConditions();
683 1
        $groupQuery = $this->groupQuery;
684 1
        $order      = $this->createQueryOrder();
685 1
        $pagination = "";
686
687 1
        if ($respectPagination) {
688 1
            $pagination = $this->createQueryPagination();
689
        }
690
691 1
        return "$extras $conditions $groupQuery $order $pagination";
692
    }
693
694
    /**
695
     * Get the query parameters
696
     *
697
     * @return array
698
     */
699 1
    protected function getParameters()
700
    {
701 1
        return array_merge($this->parameters, $this->paginationParameters);
702
    }
703
704
    /**
705
     * Get the query types
706
     *
707
     * @return string
708
     */
709 1
    protected function getTypes()
710
    {
711 1
        return $this->types . $this->paginationTypes;
712
    }
713
714
    /**
715
     * Get the table of the model
716
     *
717
     * @return string
718
     */
719 1
    protected function getTable()
720
    {
721 1
        $type = $this->type;
722
723 1
        return $type::TABLE;
724
    }
725
726
    /**
727
     * Get a MySQL query string in the requested format
728
     * @param  string|string[] $columns The columns that should be included
729
     *                                  (without the ID, if an array is provided)
730
     * @return string The query
731
     */
732 1
    protected function createQuery($columns = array())
733
    {
734 1
        $type     = $this->type;
735 1
        $table    = $type::TABLE;
736 1
        $params   = $this->createQueryParams();
737
738 1
        if (is_array($columns)) {
739 1
            $columns = $this->createQueryColumns($columns);
740
        } elseif (empty($columns)) {
741
            $columns = $this->createQueryColumns();
742
        }
743
744 1
        return "SELECT $columns FROM $table $params";
745
    }
746
747
    /**
748
     * Generate the columns for the query
749
     * @param  string[] $columns The columns that should be included (without the ID)
750
     * @return string
751
     */
752 1
    private function createQueryColumns($columns = array())
753
    {
754 1
        $type = $this->type;
755 1
        $table = $type::TABLE;
756 1
        $columnStrings = array("`$table`.id");
757
758 1
        foreach ($columns as $returnName) {
759 1
            if (strpos($returnName, ' ') === false) {
760 1
                $dbName = $this->columns[$returnName];
761 1
                $columnStrings[] = "`$table`.`$dbName` as `$returnName`";
762
            } else {
763
                // "Column" contains a space, pass it as is
764 1
                $columnStrings[] = $returnName;
765
            }
766
        }
767
768 1
        return implode(',', $columnStrings);
769
    }
770
771
    /**
772
     * Generates all the WHERE conditions for the query
773
     * @return string
774
     */
775 1
    private function createQueryConditions()
776
    {
777 1
        if ($this->conditions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->conditions of type 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...
778
            // Add parentheses around the conditions to prevent conflicts due
779
            // to the order of operations
780
            $conditions = array_map(function ($value) { return "($value)"; }, $this->conditions);
781
782 1
            return 'WHERE ' . implode(' AND ', $conditions);
783
        }
784
785
        return '';
786
    }
787
788
    /**
789
     * Generates the sorting instructions for the query
790
     * @return string
791
     */
792 1
    private function createQueryOrder()
793
    {
794 1
        if ($this->sortBy) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->sortBy of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
795 1
            $order = 'ORDER BY ' . $this->sortBy;
796
797
            // Sort by ID if the sorting columns are equal
798 1
            $id = '`' . $this->getTable() . '`.`id`';
799 1
            if ($this->reverseSort) {
800 1
                $order .= " DESC, $id DESC";
801
            } else {
802 1
                $order .= ", $id";
803
            }
804
        } else {
805 1
            $order = '';
806
        }
807
808 1
        return $order;
809
    }
810
811
    /**
812
     * Generates the pagination instructions for the query
813
     * @return string
814
     */
815 1
    private function createQueryPagination()
816
    {
817
        // Reset mysqli params and types just in case createQueryParagination()
818
        // had been called earlier
819 1
        $this->paginationParameters = array();
820 1
        $this->paginationTypes = "";
821
822 1
        if (!$this->page && !$this->limited) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->page of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
823 1
            return '';
824
        }
825
826 1
        $offset = '';
827 1
        if ($this->page) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->page of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
828 1
            $firstElement = ($this->page - 1) * $this->resultsPerPage;
829 1
            $this->paginationParameters[] = $firstElement;
830 1
            $this->paginationTypes       .= 'i';
831
832 1
            $offset = '?,';
833
        }
834
835 1
        $this->paginationParameters[] = $this->resultsPerPage;
836 1
        $this->paginationTypes       .= 'i';
837
838 1
        return "LIMIT $offset ?";
839
    }
840
}
841