Completed
Push — feature/player-elo ( 6e84c7...f9aa52 )
by Vladimir
03:15
created

QueryBuilder::createQueryParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 1
crap 2
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
    const COL_HAVING = 'having';
29
    const COL_WHERE = 'where';
30
31
    /**
32
     * The type of the model we're building a query for
33
     * @var string
34
     */
35
    protected $type;
36
37
    /**
38
     * The columns that the model provided us
39
     * @var array
40
     */
41
    protected $columns = array('id' => 'id');
42
43
    /**
44
     * Extra columns that are generated from the SQL query (this should be a comma separated string or null)
45
     * @var string|null
46
     */
47
    protected $extraColumns = null;
48
49
    /**
50
     * The conditions to include in WHERE
51
     * @var string[]
52
     */
53
    protected $whereConditions = array();
54
55
    /**
56
     * The conditions to include in HAVING
57
     * @var string[]
58
     */
59
    protected $havingConditions = array();
60
61
    /**
62
     * The MySQL value parameters
63
     * @var array
64
     */
65
    protected $parameters = array();
66
67
    /**
68
     * The MySQL value parameters for pagination
69
     * @var array
70
     */
71
    protected $paginationParameters = array();
72
73
    /**
74
     * Extra MySQL query string to pass
75
     * @var string
76
     */
77
    protected $extras = '';
78
79
    /**
80
     * Extra MySQL query groupby string to pass
81
     * @var string
82
     */
83
    protected $groupQuery = '';
84
85
    /**
86
     * A column based on which we should sort the results
87
     * @var string|null
88
     */
89
    private $sortBy = null;
90
91
    /**
92
     * Whether to reverse the results
93
     * @var bool
94
     */
95
    private $reverseSort = false;
96
97
    /**
98
     * The currently selected column
99
     * @var string|null
100
     */
101
    private $currentColumn = null;
102
103
    /**
104
     * Either 'where' or 'having'
105
     * @var string
106
     */
107
    private $currentColumnMode = '';
108
109
    /**
110
     * The currently selected column without the table name (unless it was
111
     * explicitly provided)
112
     * @var string|null
113
     */
114
    protected $currentColumnRaw = null;
115
116
    /**
117
     * A column to consider the name of the model
118
     * @var string|null
119
     */
120
    private $nameColumn = null;
121
122
    /**
123
     * The page to return
124
     * @var int|null
125
     */
126
    private $page = null;
127
128
    /**
129
     * Whether the ID of the first/last element has been provided
130
     * @var bool
131
     */
132
    private $limited = false;
133
134
    /**
135
     * The number of elements on every page
136
     * @var int
137
     */
138
    protected $resultsPerPage = 30;
139
140
    /**
141
     * Create a new QueryBuilder
142
     *
143
     * A new query builder should be created on a static getQueryBuilder()
144
     * method on each model. The options array can contain the following
145
     * properties:
146
     *
147
     * - `columns`: An associative array - the key of each entry is the column
148
     *   name that will be used by other methods, while the value is
149
     *   is the column name that is used in the database structure
150
     *
151
     * - `activeStatuses`: If the model has a status column, this should be
152
     *                     a list of values that make the entry be considered
153
     *                     "active"
154
     *
155
     * - `name`: The name of the column which represents the name of the object
156
     *
157
     * @param string $type    The type of the Model (e.g. "Player" or "Match")
158
     * @param array  $options The options to pass to the builder (see above)
159
     */
160 4
    public function __construct($type, $options = array())
161
    {
162 4
        $this->type = $type;
163
164 4
        if (isset($options['columns'])) {
165 4
            $this->columns += $options['columns'];
166
        }
167
168 4
        if (isset($options['name'])) {
169 2
            $this->nameColumn = $options['name'];
170
        }
171 4
    }
172
173
    /**
174
     * Select a column
175
     *
176
     * `$queryBuilder->where('username')->equals('administrator');`
177
     *
178
     * @param  string $column The column to select
179
     * @return static
180
     */
181 4
    public function where($column)
182
    {
183 4
        return $this->grabColumn($column, 'where');
184
    }
185
186
    /**
187
     * Select an alias from an aggregate function
188
     *
189
     * `$queryBuilder->where('activity')->greaterThan(0);`
190
     *
191
     * @param  string $column The column to select
192
     * @return static
193
     */
194
    public function having($column)
195
    {
196
        return $this->grabColumn($column, 'having');
197
    }
198
199
    /**
200
     * Request that a column equals a string (case-insensitive)
201
     *
202
     * @param  string $string The string that the column's value should equal to
203
     * @return static
204
     */
205 2
    public function equals($string)
206
    {
207 2
        $this->addColumnCondition("= ?", $string);
208
209 2
        return $this;
210
    }
211
212
    /**
213
     * Request that a column doesNOT equals a string (case-insensitive)
214
     *
215
     * @param  string $string The string that the column's value should equal to
216
     * @return static
217
     */
218 1
    public function notEquals($string)
219
    {
220 1
        $this->addColumnCondition("!= ?", $string);
221
222 1
        return $this;
223
    }
224
225
    /**
226
     * Request that a column is not null
227
     *
228
     * @return static
229
     */
230 1
    public function isNotNull()
231
    {
232 1
        $this->addColumnCondition('IS NOT NULL', null);
233
234 1
        return $this;
235
    }
236
237
    /**
238
     * Request that a column is null
239
     *
240
     * @return static
241
     */
242
    public function isNull()
243
    {
244
        $this->addColumnCondition('IS NULL', null);
245
246
        return $this;
247
    }
248
249
    /**
250
     * Request that a column is greater than a quantity
251
     *
252
     * @param  string $quantity The quantity to test against
253
     * @return static
254
     */
255
    public function greaterThan($quantity)
256
    {
257
        $this->addColumnCondition("> ?", $quantity);
258
259
        return $this;
260
    }
261
262
    /**
263
     * Request that a column is less than a quantity
264
     *
265
     * @param  string $quantity The quantity to test against
266
     * @return static
267
     */
268
    public function lessThan($quantity)
269
    {
270
        $this->addColumnCondition("< ?", $quantity);
271
272
        return $this;
273
    }
274
275
    /**
276
     * Request that a timestamp is before the specified time
277
     *
278
     * @param string|TimeDate $time      The timestamp to compare to
279
     * @param bool            $inclusive Whether to include the given timestamp
280
     * @param bool            $reverse   Whether to reverse the results
281
     *
282
     * @return static
283
     */
284
    public function isBefore($time, $inclusive = false, $reverse = false)
285
    {
286
        return $this->isAfter($time, $inclusive, !$reverse);
287
    }
288
289
    /**
290
     * Request that a timestamp is after the specified time
291
     *
292
     * @param string|TimeDate $time      The timestamp to compare to
293
     * @param bool            $inclusive Whether to include the given timestamp
294
     * @param bool            $reverse   Whether to reverse the results
295
     *
296
     * @return static
297
     */
298 1
    public function isAfter($time, $inclusive = false, $reverse = false)
299
    {
300 1
        if ($time instanceof TimeDate) {
301 1
            $time = $time->toMysql();
302
        }
303
304 1
        $comparison  = ($reverse)   ? '<' : '>';
305 1
        $comparison .= ($inclusive) ? '=' : '';
306
307 1
        $this->addColumnCondition("$comparison ?",  $time);
308
309 1
        return $this;
310
    }
311
312
    /**
313
     * Request that a column equals a number
314
     *
315
     * @param  int|Model|null $number The number that the column's value should
316
     *                                equal to. If a Model is provided, use the
317
     *                                model's ID, while null values are ignored.
318
     * @return static
319
     */
320 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...
321
    {
322 1
        if ($number === null) {
323
            return $this;
324
        }
325
326 1
        if ($number instanceof Model) {
327 1
            $number = $number->getId();
328
        }
329
330 1
        $this->addColumnCondition("= ?", $number);
331
332 1
        return $this;
333
    }
334
335
    /**
336
     * Request that a column equals one of some strings
337
     *
338
     * @todo   Improve for PDO
339
     * @param  string[] $strings The list of accepted values for the column
340
     * @return static
341
     */
342 3
    public function isOneOf($strings)
343
    {
344 3
        $count = count($strings);
345 3
        $questionMarks = str_repeat(',?', $count);
346
347
        // Remove first comma from questionMarks so that MySQL can read our query
348 3
        $questionMarks = ltrim($questionMarks, ',');
349
350 3
        $this->addColumnCondition("IN ($questionMarks)", $strings);
351
352 3
        return $this;
353
    }
354
355
    /**
356
     * Request that a column value starts with a string (case-insensitive)
357
     *
358
     * @param  string $string The substring that the column's value should start with
359
     * @return static
360
     */
361
    public function startsWith($string)
362
    {
363
        $this->addColumnCondition("LIKE CONCAT(?, '%')", $string);
364
365
        return $this;
366
    }
367
368
    /**
369
     * Request that a specific model is not returned
370
     *
371
     * @param  Model|int $model The ID or model you don't want to get
372
     * @return static
373
     */
374 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...
375
    {
376
        if ($model instanceof Model) {
377
            $model = $model->getId();
378
        }
379
380
        $this->where('id');
381
        $this->addColumnCondition("!= ?", $model);
382
383
        return $this;
384
    }
385
386
    /**
387
     * Return the results sorted by the value of a column
388
     *
389
     * @param  string $column The column based on which the results should be ordered
390
     * @return static
391
     */
392 2
    public function sortBy($column)
393
    {
394 2
        if (!isset($this->columns[$column])) {
395
            throw new Exception("Unknown column");
396
        }
397
398 2
        $this->sortBy = $this->columns[$column];
399
400 2
        return $this;
401
    }
402
403
    /**
404
     * Reverse the order
405
     *
406
     * Note: This only works if you have specified a column in the sortBy() method
407
     *
408
     * @return static
409
     */
410 2
    public function reverse()
411
    {
412 2
        $this->reverseSort = !$this->reverseSort;
413
414 2
        return $this;
415
    }
416
417
    /**
418
     * Specify the number of results per page
419
     *
420
     * @param  int  $count The number of results
421
     * @return static
422
     */
423 2
    public function limit($count)
424
    {
425 2
        $this->resultsPerPage = $count;
426
427 2
        return $this;
428
    }
429
430
    /**
431
     * Only show results from a specific page
432
     *
433
     * @param  int|null $page The page number (or null to show all pages - counting starts from 0)
434
     * @return static
435
     */
436 2
    public function fromPage($page)
437
    {
438 2
        $this->page = $page;
439
440 2
        return $this;
441
    }
442
443
    /**
444
     * End with a specific result
445
     *
446
     * @param  int|Model $model     The model (or database ID) after the first result
447
     * @param  bool   $inclusive Whether to include the provided model
448
     * @param  bool   $reverse   Whether to reverse the results
449
     * @return static
450
     */
451 1
    public function endAt($model, $inclusive = false, $reverse = false)
452
    {
453 1
        return $this->startAt($model, $inclusive, !$reverse);
454
    }
455
456
    /**
457
     * Start with a specific result
458
     *
459
     * @param  int|Model $model     The model (or database ID) before the first result
460
     * @param  bool   $inclusive Whether to include the provided model
461
     * @param  bool   $reverse   Whether to reverse the results
462
     * @return static
463
     */
464 1
    public function startAt($model, $inclusive = false, $reverse = false)
465
    {
466 1
        if (!$model) {
467 1
            return $this;
468
        } elseif ($model instanceof Model && !$model->isValid()) {
469
            return $this;
470
        }
471
472
        $this->column($this->sortBy);
473
        $this->limited = true;
474
        $column = $this->currentColumn;
475
        $table  = $this->getTable();
476
477
        $comparison  = $this->reverseSort ^ $reverse;
478
        $comparison  = ($comparison) ? '>' : '<';
479
        $comparison .= ($inclusive)  ? '=' : '';
480
        $id = ($model instanceof Model) ? $model->getId() : $model;
481
482
        // Compare an element's timestamp to the timestamp of $model; if it's the
483
        // same, perform the comparison using IDs
484
        $this->addColumnCondition(
485
            "$comparison (SELECT $column FROM $table WHERE id = ?) OR ($column = (SELECT $column FROM $table WHERE id = ?) AND id $comparison ?)",
486
            array($id, $id, $id)
487
        );
488
489
        return $this;
490
    }
491
492
    /**
493
     * Request that only "active" Models should be returned
494
     *
495
     * @return static
496
     */
497 3
    public function active()
498
    {
499 3
        if (!isset($this->columns['status'])) {
500
            return $this;
501
        }
502
503 3
        $type = $this->type;
504
505 3
        return $this->where('status')->isOneOf($type::getActiveStatuses());
506
    }
507
508
    /**
509
     * Make sure that Models invisible to a player are not returned
510
     *
511
     * Note that this method does not take PermissionModel::canBeSeenBy() into
512
     * consideration for performance purposes, so you will have to override this
513
     * in your query builder if necessary.
514
     *
515
     * @param  Player  $player      The player in question
516
     * @param  bool $showDeleted false to hide deleted models even from admins
517
     * @return static
518
     */
519 1
    public function visibleTo($player, $showDeleted = false)
520
    {
521 1
        $type = $this->type;
522
523 1
        if (is_subclass_of($type, "PermissionModel")
524 1
         && $player->hasPermission($type::EDIT_PERMISSION)) {
525
            // The player is an admin who can see hidden models
526 1
            if (!$showDeleted) {
527 1
                if (isset($this->columns['status'])) {
528 1
                    return $this->where('status')->notEquals('deleted');
529
                }
530
            }
531
        } else {
532 1
            return $this->active();
533
        }
534
535
        return $this;
536
    }
537
538
    /**
539
     * Perform the query and get back the results in an array of names
540
     *
541
     * @return string[] An array of the type $id => $name
542
     */
543 1
    public function getNames()
544
    {
545 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...
546
            throw new Exception("You haven't specified a name column");
547
        }
548
549 1
        $results = $this->getArray($this->nameColumn);
550
551 1
        return array_column($results, $this->nameColumn, 'id');
552
    }
553
554
    /**
555
     * Perform the query and get back the results in a list of arrays
556
     *
557
     * @todo   Play with partial models?
558
     * @param  string|string[] $columns The column(s) that should be returned
559
     * @return array[]
560
     */
561 1
    public function getArray($columns)
562
    {
563 1
        if (!is_array($columns)) {
564 1
            $columns = array($columns);
565
        }
566
567 1
        $db = Database::getInstance();
568
569 1
        return $db->query($this->createQuery($columns), $this->getParameters());
570
    }
571
572
    /**
573
     * An alias for QueryBuilder::getModels(), with fast fetching on by default
574
     * and no return of results
575
     *
576
     * @param  bool $fastFetch Whether to perform one query to load all
577
     *                            the model data instead of fetching them
578
     *                            one by one
579
     * @return void
580
     */
581
    public function addToCache($fastFetch = true)
582
    {
583
        $this->getModels($fastFetch);
584
    }
585
586
    /**
587
     * Perform the query and get the results as Models
588
     *
589
     * @todo Fix fast fetch for queries with multiple tables
590
     * @param  bool $fastFetch Whether to perform one query to load all
591
     *                            the model data instead of fetching them
592
     *                            one by one (ignores cache)
593
     * @return array
594
     */
595 4
    public function getModels($fastFetch = false)
596
    {
597 4
        $db   = Database::getInstance();
598 4
        $type = $this->type;
599
600 4
        $columns = ($fastFetch) ? $type::getEagerColumns($this->getFromAlias()) : array();
601
602 4
        if (is_string($columns) && !empty($this->extraColumns)) {
603
            $columns .= ',' . $this->extraColumns;
604
        }
605
606
        // Storing the value in a variable allows for quicker debugging
607 4
        $query = $this->createQuery($columns);
608 4
        $results = $db->query($query, $this->getParameters());
609
610 4
        if ($fastFetch) {
611 2
            return $type::createFromDatabaseResults($results);
612
        } else {
613 3
            return $type::arrayIdToModel(array_column($results, 'id'));
614
        }
615
    }
616
617
    /**
618
     * Count the results
619
     *
620
     * @return int
621
     */
622 1
    public function count()
623
    {
624 1
        $table  = $this->getTable();
625 1
        $params = $this->createQueryParams(false);
626 1
        $db     = Database::getInstance();
627 1
        $query  = "SELECT COUNT(*) FROM $table $params";
628
629
        // We don't want pagination to affect our results so don't use the functions that combine
630
        // pagination results
631 1
        $results = $db->query($query, $this->parameters);
632
633 1
        return $results[0]['COUNT(*)'];
634
    }
635
636
    /**
637
     * Count the number of pages that all the models could be separated into
638
     */
639 1
    public function countPages()
640
    {
641 1
        return ceil($this->count() / $this->getResultsPerPage());
642
    }
643
644
    /**
645
     * Find if there is any result
646
     *
647
     * @return bool
648
     */
649 1
    public function any()
650
    {
651
        // Make sure that we don't mess with the user's options
652 1
        $query = clone $this;
653
654 1
        $query->limit(1);
655
656 1
        return $query->count() > 0;
657
    }
658
659
    /**
660
     * Get the amount of results that are returned per page
661
     * @return int
662
     */
663 1
    public function getResultsPerPage()
664
    {
665 1
        return $this->resultsPerPage;
666
    }
667
668
    /**
669
     * Select a column to perform opeations on
670
     *
671
     * This is identical to the `where()` method, except that the column is
672
     * specified as a MySQL column and not as a column name given by the model
673
     *
674
     * @param  string $column The column to select
675
     * @param  string $mode   Whether this column is static or is a column from an aggregate function; Either 'having' or 'where'
676
     *
677
     * @return static
678
     */
679 4
    protected function column($column, $mode = self::COL_WHERE)
680
    {
681 4
        $this->currentColumnMode = $mode;
682
683 4
        if (strpos($column, '.') === false) {
684
            // Add the table name to the column if it isn't there already so that
685
            // MySQL knows what to do when handling multiple tables
686 4
            $this->currentColumn = ($this->currentColumnMode == self::COL_HAVING) ? "$column" : "`{$this->getFromAlias()}`.`$column`";
687
        } else {
688 1
            $this->currentColumn = $column;
689
        }
690
691 4
        $this->currentColumnRaw = $column;
692
693 4
        return $this;
694
    }
695
696
    /**
697
     * Add a condition for the column
698
     * @param  string $condition The MySQL condition
699
     * @param  mixed  $value     Value(s) to pass to MySQL
700
     * @return void
701
     */
702 4
    protected function addColumnCondition($condition, $value)
703
    {
704 4
        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...
705
            throw new Exception("You haven't selected a column!");
706
        }
707
708 4
        if (!is_array($value) && $value !== null) {
709 2
            $value = array($value);
710
        }
711
712 4
        $array = $this->currentColumnMode . 'Conditions';
713 4
        $this->{$array}[] = "{$this->currentColumn} $condition";
714
715 4
        if ($value !== null) {
716 4
            $this->parameters = array_merge($this->parameters, $value);
717
        }
718
719 4
        $this->currentColumn = null;
720 4
        $this->currentColumnRaw = null;
721 4
    }
722
723
    /**
724
     * Get the MySQL extra parameters
725
     *
726
     * @param  bool $respectPagination Whether to respect pagination or not; useful for when pagination should be ignored such as count
727
     * @return string
728
     */
729 4
    protected function createQueryParams($respectPagination = true)
730
    {
731 4
        $extras     = $this->extras;
732 4
        $conditions = $this->createQueryConditions('where');
733 4
        $groupQuery = $this->groupQuery;
734 4
        $havingClause = $this->createQueryConditions('having');
735 4
        $order      = $this->createQueryOrder();
736 4
        $pagination = "";
737
738 4
        if ($respectPagination) {
739 4
            $pagination = $this->createQueryPagination();
740
        }
741
742 4
        return "$extras $conditions $groupQuery $havingClause $order $pagination";
743
    }
744
745
    /**
746
     * Get the query parameters
747
     *
748
     * @return array
749
     */
750 4
    protected function getParameters()
751
    {
752 4
        return array_merge($this->parameters, $this->paginationParameters);
753
    }
754
755
    /**
756
     * Get the alias used for the table in the FROM clause
757
     *
758
     * @return null|string
759
     */
760 4
    protected function getFromAlias()
761
    {
762 4
        return $this->getTable();
763
    }
764
765
    /**
766
     * Get the table of the model
767
     *
768
     * @return string
769
     */
770 4
    protected function getTable()
771
    {
772 4
        $type = $this->type;
773
774 4
        return $type::TABLE;
775
    }
776
777
    /**
778
     * Get a MySQL query string in the requested format
779
     * @param  string|string[] $columns The columns that should be included
780
     *                                  (without the ID, if an array is provided)
781
     * @return string The query
782
     */
783 4
    protected function createQuery($columns = array())
784
    {
785 4
        $type     = $this->type;
786 4
        $table    = $type::TABLE;
787 4
        $params   = $this->createQueryParams();
788
789 4
        if (is_array($columns)) {
790 3
            $columns = $this->createQueryColumns($columns);
791
        } elseif (empty($columns)) {
792
            $columns = $this->createQueryColumns();
793
        }
794
795 4
        return "SELECT $columns FROM $table $params";
796
    }
797
798
    /**
799
     * Generate the columns for the query
800
     * @param  string[] $columns The columns that should be included (without the ID)
801
     * @return string
802
     */
803 3
    private function createQueryColumns($columns = array())
804
    {
805 3
        $type = $this->type;
806 3
        $table = $type::TABLE;
807 3
        $columnStrings = array("`$table`.id");
808
809 3
        foreach ($columns as $returnName) {
810 1
            if (strpos($returnName, ' ') === false) {
811 1
                $dbName = $this->columns[$returnName];
812 1
                $columnStrings[] = "`$table`.`$dbName` as `$returnName`";
813
            } else {
814
                // "Column" contains a space, pass it as is
815 1
                $columnStrings[] = $returnName;
816
            }
817
        }
818
819 3
        return implode(',', $columnStrings);
820
    }
821
822
    /**
823
     * Generates all the WHERE conditions for the query
824
     * @return string
825
     */
826 4
    private function createQueryConditions($mode)
827
    {
828 4
        $array = $mode . 'Conditions';
829
830 4
        if ($this->{$array}) {
831
            // Add parentheses around the conditions to prevent conflicts due
832
            // to the order of operations
833
            $conditions = array_map(function ($value) { return "($value)"; }, $this->{$array});
834
835 4
            return strtoupper($mode) . ' ' . implode(' AND ', $conditions);
836
        }
837
838 4
        return '';
839
    }
840
841
    /**
842
     * Generates the sorting instructions for the query
843
     * @return string
844
     */
845 4
    private function createQueryOrder()
846
    {
847 4
        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...
848 2
            $order = 'ORDER BY ' . $this->sortBy;
849
850
            // Sort by ID if the sorting columns are equal
851 2
            $id = "`{$this->getFromAlias()}`.`id`";
852 2
            if ($this->reverseSort) {
853 2
                $order .= " DESC, $id DESC";
854
            } else {
855 2
                $order .= ", $id";
856
            }
857
        } else {
858 3
            $order = '';
859
        }
860
861 4
        return $order;
862
    }
863
864
    /**
865
     * Generates the pagination instructions for the query
866
     * @return string
867
     */
868 4
    private function createQueryPagination()
869
    {
870
        // Reset mysqli params just in case createQueryParagination()
871
        // had been called earlier
872 4
        $this->paginationParameters = array();
873
874 4
        if ($this->page === null && !$this->limited) {
875 3
            return '';
876
        }
877
878 2
        $offset = '';
879 2
        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...
880 2
            $firstElement = ($this->page - 1) * $this->resultsPerPage;
881 2
            $this->paginationParameters[] = $firstElement;
882
883 2
            $offset = '?,';
884
        }
885
886 2
        $this->paginationParameters[] = $this->resultsPerPage;
887
888 2
        return "LIMIT $offset ?";
889
    }
890
891
    /**
892
     * Set the current column we're working on
893
     *
894
     * @param string $column The column we're selecting
895
     * @param string $mode   Either 'where' or 'having'
896
     *
897
     * @return $this
898
     */
899 4
    private function grabColumn($column, $mode)
900
    {
901 4
        if (!isset($this->columns[$column])) {
902
            throw new InvalidArgumentException("Unknown column '$column'");
903
        }
904
905 4
        $this->column($this->columns[$column], $mode);
906
907 4
        return $this;
908
    }
909
}
910