-
Notifications
You must be signed in to change notification settings - Fork 29
/
Query.php
3171 lines (2624 loc) · 79.7 KB
/
Query.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Base Custom Database Table Query Class.
*
* @package Database
* @subpackage Query
* @copyright Copyright (c) 2021
* @license https://opensource.org/licenses/MIT MIT
* @since 1.0.0
*/
namespace BerlinDB\Database;
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
/**
* Base class used for querying custom database tables.
*
* This class is intended to be extended for each unique database table,
* including global tables for multisite, and users tables.
*
* @since 1.0.0
*
* @see Query::__construct() for accepted arguments.
*
* @property string $prefix
* @property string $table_name
* @property string $table_alias
* @property string $table_schema
* @property string $item_name
* @property string $item_name_plural
* @property string $item_shape
* @property string $cache_group
* @property int $last_changed
* @property array $columns
* @property array $query_clauses
* @property array $request_clauses
* @property Queries\Meta $meta_query
* @property Queries\Date $date_query
* @property Queries\Compare $compare_query
* @property array $query_vars
* @property array $query_var_originals
* @property array $query_var_defaults
* @property string $query_var_default_value
* @property array $items
* @property int $found_items
* @property int $max_num_pages
* @property string $request
*/
class Query extends Base {
/** Table Properties ******************************************************/
/**
* Name of the database table to query.
*
* @since 1.0.0
* @var string
*/
protected $table_name = '';
/**
* String used to alias the database table in MySQL statement.
*
* Keep this short, but descriptive. I.E. "tr" for term relationships.
*
* This is used to avoid collisions with JOINs.
*
* @since 1.0.0
* @var string
*/
protected $table_alias = '';
/**
* Name of class used to setup the database schema.
*
* @since 1.0.0
* @var string
*/
protected $table_schema = '\\BerlinDB\\Database\\Schema';
/** Item ******************************************************************/
/**
* Name for a single item.
*
* Use underscores between words. I.E. "term_relationship"
*
* This is used to automatically generate action hooks.
*
* @since 1.0.0
* @var string
*/
protected $item_name = '';
/**
* Plural version for a group of items.
*
* Use underscores between words. I.E. "term_relationships"
*
* This is used to automatically generate action hooks.
*
* @since 1.0.0
* @var string
*/
protected $item_name_plural = '';
/**
* Name of class used to turn IDs into first-class objects.
*
* This is used when looping through return values to guarantee their shape.
*
* @since 1.0.0
* @var mixed
*/
protected $item_shape = '\\BerlinDB\\Database\\Row';
/**
* Name of class used to turn IDs into first-class objects for the current request.
*
* This is used when looping through return values to guarantee their shape.
*
* @var mixed
*/
protected $current_item_shape;
/** Cache *****************************************************************/
/**
* Group to cache queries and queried items in.
*
* Use underscores between words. I.E. "some_items"
*
* Do not use colons: ":". These are reserved for internal use only.
*
* @since 1.0.0
* @var string
*/
protected $cache_group = '';
/**
* The last updated time.
*
* @since 1.0.0
* @var int
*/
protected $last_changed = 0;
/** Columns ***************************************************************/
/**
* Array of all database column objects.
*
* @since 1.0.0
* @var array
*/
protected $columns = array();
/** Clauses ***************************************************************/
/**
* SQL query clauses.
*
* @since 1.0.0
* @var array
*/
protected $query_clauses = array(
'select' => '',
'from' => '',
'where' => array(),
'groupby' => '',
'orderby' => '',
'limits' => ''
);
/**
* Request clauses.
*
* @since 1.0.0
* @var array
*/
protected $request_clauses = array(
'select' => '',
'from' => '',
'where' => '',
'groupby' => '',
'orderby' => '',
'limits' => ''
);
/**
* Meta query container.
*
* @since 1.0.0
* @var object|Queries\Meta
*/
protected $meta_query = false;
/**
* Date query container.
*
* @since 1.0.0
* @var object|Queries\Date
*/
protected $date_query = false;
/**
* Compare query container.
*
* @since 1.0.0
* @var object|Queries\Compare
*/
protected $compare_query = false;
/** Query Variables *******************************************************/
/**
* Parsed query vars set by the application, possibly filtered and changed.
*
* This is specifically marked as public, to allow byref actions to change
* them from outside the class methods proper and inside filter functions.
*
* @since 1.0.0
* @var array
*/
public $query_vars = array();
/**
* Original query vars set by the application.
*
* These are the original query variables before any filters are applied,
* and are the results of merging $query_var_defaults with $query_vars.
*
* @since 1.0.0
* @var array
*/
protected $query_var_originals = array();
/**
* Default values for query vars.
*
* These are computed at runtime based on the registered columns for the
* database table this query relates to.
*
* @since 1.0.0
* @var array
*/
protected $query_var_defaults = array();
/**
* This private variable temporarily holds onto a random string used as the
* default query var value. This is used internally when performing
* comparisons, and allows for querying by falsy values.
*
* @since 1.1.0
* @var string
*/
protected $query_var_default_value = '';
/** Results ***************************************************************/
/**
* List of items located by the query.
*
* @since 1.0.0
* @var array
*/
public $items = array();
/**
* The amount of found items for the current query.
*
* @since 1.0.0
* @var int
*/
protected $found_items = 0;
/**
* The number of pages.
*
* @since 1.0.0
* @var int
*/
protected $max_num_pages = 0;
/**
* SQL for database query.
*
* @since 1.0.0
* @var string
*/
protected $request = '';
/** Methods ***************************************************************/
/**
* Sets up the item query, based on the query vars passed.
*
* @since 1.0.0
*
* @param string|array $query {
* Optional. Array or query string of item query parameters.
* Default empty.
*
* @type string $fields Site fields to return. Accepts 'ids' (returns an array of item IDs)
* or empty (returns an array of complete item objects). Default empty.
* To do a date query against a field, append the field name with _query
* @type bool $count Whether to return a item count (true) or array of item objects.
* Default false.
* @type int $number Limit number of items to retrieve. Use 0 for no limit.
* Default 100.
* @type int $offset Number of items to offset the query. Used to build LIMIT clause.
* Default 0.
* @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
* Default true.
* @type string|array $orderby Accepts false, an empty array, or 'none' to disable `ORDER BY` clause.
* Default '', to primary column ID.
* @type string $order How to order retrieved items. Accepts 'ASC', 'DESC'.
* Default 'DESC'.
* @type string $search Search term(s) to retrieve matching items for.
* Default empty.
* @type array $search_columns Array of column names to be searched.
* Default empty array.
* @type bool $update_item_cache Whether to prime the cache for found items.
* Default false.
* @type bool $update_meta_cache Whether to prime the meta cache for found items.
* Default false.
* }
*/
public function __construct( $query = array() ) {
// Setup
$this->set_alias();
$this->set_prefix();
$this->set_columns();
$this->set_item_shape();
$this->set_query_var_defaults();
// Maybe execute a query if arguments were passed
if ( ! empty( $query ) ) {
$this->query( $query );
}
}
/**
* Queries the database and retrieves items or counts.
*
* This method is public to allow subclasses to perform JIT manipulation
* of the parameters passed into it.
*
* @since 1.0.0
*
* @param string|array $query Array or URL query string of parameters.
* @return array|int List of items, or number of items when 'count' is passed as a query var.
*/
public function query( $query = array() ) {
$this->parse_query( $query );
return $this->get_items();
}
/** Private Setters *******************************************************/
/**
* Set the time when items were last changed.
*
* We set this locally to avoid inconsistencies between method calls.
*
* @since 1.0.0
*/
private function set_last_changed() {
$this->last_changed = microtime();
}
/**
* Set up the table alias if not already set in the class.
*
* This happens before prefixes are applied.
*
* @since 1.0.0
*/
private function set_alias() {
if ( empty( $this->table_alias ) ) {
$this->table_alias = $this->first_letters( $this->table_name );
}
}
/**
* Prefix table names, cache groups, and other things.
*
* This is to avoid conflicts with other plugins or themes that might be
* doing their own things.
*
* @since 1.0.0
*/
private function set_prefix() {
$this->table_name = $this->apply_prefix( $this->table_name );
$this->table_alias = $this->apply_prefix( $this->table_alias );
$this->cache_group = $this->apply_prefix( $this->cache_group, '-' );
}
/**
* Set columns objects.
*
* @since 1.0.0
*/
private function set_columns() {
// Bail if no table schema
if ( ! class_exists( $this->table_schema ) ) {
return;
}
// Invoke a new table schema class
$schema = new $this->table_schema;
// Maybe get the column objects
if ( ! empty( $schema->columns ) ) {
$this->columns = $schema->columns;
}
}
/**
* Set the default item shape if none exists.
*
* @since 1.0.0
*/
private function set_item_shape() {
if ( empty( $this->item_shape ) || ! class_exists( $this->item_shape ) ) {
$this->item_shape = __NAMESPACE__ . '\\Row';
}
if ( empty( $this->current_item_shape ) || ! class_exists( $this->current_item_shape ) ) {
$this->current_item_shape = $this->item_shape;
}
}
/**
* Set default query vars based on columns.
*
* @since 1.0.0
*/
private function set_query_var_defaults() {
// Default query variable value
$this->query_var_default_value = function_exists( 'random_bytes' )
? $this->apply_prefix( bin2hex( random_bytes( 18 ) ) )
: $this->apply_prefix( uniqid( '_', true ) );
// Get the primary column name
$primary = $this->get_primary_column_name();
// Default query variables
$this->query_var_defaults = array(
'fields' => '',
'number' => 100,
'offset' => '',
'orderby' => $primary,
'order' => 'DESC',
'groupby' => '',
'search' => '',
'search_columns' => array(),
'count' => false,
// Disable SQL_CALC_FOUND_ROWS?
'no_found_rows' => true,
// Queries
'meta_query' => null, // See Queries\Meta
'date_query' => null, // See Queries\Date
'compare_query' => null, // See Queries\Compare
// Caching
'update_item_cache' => true,
'update_meta_cache' => true
);
// Bail if no columns
if ( empty( $this->columns ) ) {
return;
}
// Direct column names
$names = wp_list_pluck( $this->columns, 'name' );
foreach ( $names as $name ) {
$this->query_var_defaults[ $name ] = $this->query_var_default_value;
}
// Possible ins
$possible_ins = $this->get_columns( array( 'in' => true ), 'and', 'name' );
foreach ( $possible_ins as $in ) {
$key = "{$in}__in";
$this->query_var_defaults[ $key ] = false;
}
// Possible not ins
$possible_not_ins = $this->get_columns( array( 'not_in' => true ), 'and', 'name' );
foreach ( $possible_not_ins as $in ) {
$key = "{$in}__not_in";
$this->query_var_defaults[ $key ] = false;
}
// Possible dates
$possible_dates = $this->get_columns( array( 'date_query' => true ), 'and', 'name' );
foreach ( $possible_dates as $date ) {
$key = "{$date}_query";
$this->query_var_defaults[ $key ] = false;
}
}
/**
* Set the request clauses.
*
* @since 1.0.0
*
* @param array $clauses
*/
private function set_request_clauses( $clauses = array() ) {
// Found rows
$found_rows = empty( $this->query_vars['no_found_rows'] )
? 'SQL_CALC_FOUND_ROWS'
: '';
// Fields
$fields = ! empty( $clauses['fields'] )
? $clauses['fields']
: '';
// Join
$join = ! empty( $clauses['join'] )
? $clauses['join']
: '';
// Where
$where = ! empty( $clauses['where'] )
? "WHERE {$clauses['where']}"
: '';
// Group by
$groupby = ! empty( $clauses['groupby'] )
? "GROUP BY {$clauses['groupby']}"
: '';
// Order by
$orderby = ! empty( $clauses['orderby'] )
? "ORDER BY {$clauses['orderby']}"
: '';
// Limits
$limits = ! empty( $clauses['limits'] )
? $clauses['limits']
: '';
// Select & From
$table = $this->get_table_name();
$select = "SELECT {$found_rows} {$fields}";
$from = "FROM {$table} {$this->table_alias} {$join}";
// Put query into clauses array
$this->request_clauses['select'] = $select;
$this->request_clauses['from'] = $from;
$this->request_clauses['where'] = $where;
$this->request_clauses['groupby'] = $groupby;
$this->request_clauses['orderby'] = $orderby;
$this->request_clauses['limits'] = $limits;
}
/**
* Set the request.
*
* @since 1.0.0
*/
private function set_request() {
$filtered = array_filter( $this->request_clauses );
$clauses = array_map( 'trim', $filtered );
$this->request = implode( ' ', $clauses );
}
/**
* Set items by mapping them through the single item callback.
*
* @since 1.0.0
* @param array $item_ids
*/
private function set_items( $item_ids = array() ) {
// Bail if counting, to avoid shaping items
if ( ! empty( $this->query_vars['count'] ) ) {
$this->items = $item_ids;
return;
}
// Cast to integers
$item_ids = array_map( 'intval', $item_ids );
// Prime item caches
$this->prime_item_caches( $item_ids );
// Shape the items
$this->items = $this->shape_items( $item_ids );
}
/**
* Populates found_items and max_num_pages properties for the current query
* if the limit clause was used.
*
* @since 1.0.0
*
* @param array $item_ids Optional array of item IDs
*/
private function set_found_items( $item_ids = array() ) {
// Items were not found
if ( empty( $item_ids ) ) {
return;
}
// Default to number of item IDs
$this->found_items = count( (array) $item_ids );
// Count query
if ( ! empty( $this->query_vars['count'] ) ) {
// Not grouped
if ( is_numeric( $item_ids ) && empty( $this->query_vars['groupby'] ) ) {
$this->found_items = intval( $item_ids );
}
// Not a count query
} elseif ( is_array( $item_ids ) && ( ! empty( $this->query_vars['number'] ) && empty( $this->query_vars['no_found_rows'] ) ) ) {
/**
* Filters the query used to retrieve found item count.
*
* @since 1.0.0
*
* @param string $found_items_query SQL query. Default 'SELECT FOUND_ROWS()'.
* @param object $item_query The object instance.
*/
$found_items_query = (string) apply_filters_ref_array( $this->apply_prefix( "found_{$this->item_name_plural}_query" ), array( 'SELECT FOUND_ROWS()', &$this ) );
// Maybe query for found items
if ( ! empty( $found_items_query ) ) {
$this->found_items = (int) $this->get_db()->get_var( $found_items_query );
}
}
}
/** Public Setters ********************************************************/
/**
* Set a query var, to both defaults and request arrays.
*
* This method is used to expose the private query_vars array to hooks,
* allowing them to manipulate query vars just-in-time.
*
* @since 1.0.0
*
* @param string $key
* @param string $value
*/
public function set_query_var( $key = '', $value = '' ) {
$this->query_var_defaults[ $key ] = $value;
$this->query_vars[ $key ] = $value;
}
/**
* Check whether a query variable strictly equals the unique default
* starting value.
*
* @since 1.1.0
* @param string $key
* @return bool
*/
public function is_query_var_default( $key = '' ) {
return (bool) ( $this->query_vars[ $key ] === $this->query_var_default_value );
}
/** Private Getters *******************************************************/
/**
* Pass-through method to return a new Meta object.
*
* @since 1.0.0
*
* @param array $args See Queries\Meta
*
* @return Queries\Meta
*/
private function get_meta_query( $args = array() ) {
return new Queries\Meta( $args );
}
/**
* Pass-through method to return a new Compare object.
*
* @since 1.0.0
*
* @param array $args See Queries\Compare
*
* @return Queries\Compare
*/
private function get_compare_query( $args = array() ) {
return new Queries\Compare( $args );
}
/**
* Pass-through method to return a new Queries\Date object.
*
* @since 1.0.0
*
* @param array $args See Queries\Date
*
* @return Queries\Date
*/
private function get_date_query( $args = array() ) {
return new Queries\Date( $args );
}
/**
* Return the current time as a UTC timestamp.
*
* This is used by add_item() and update_item()
*
* @since 1.0.0
*
* @return string
*/
private function get_current_time() {
return gmdate( "Y-m-d\TH:i:s\Z" );
}
/**
* Return the literal table name (with prefix) from the database interface.
*
* @since 1.0.0
*
* @return string
*/
private function get_table_name() {
return $this->get_db()->{$this->table_name};
}
/**
* Return array of column names.
*
* @since 1.0.0
*
* @return array
*/
private function get_column_names() {
return array_flip( $this->get_columns( array(), 'and', 'name' ) );
}
/**
* Return the primary database column name.
*
* @since 1.0.0
*
* @return string Default "id", Primary column name if not empty
*/
private function get_primary_column_name() {
return $this->get_column_field( array( 'primary' => true ), 'name', 'id' );
}
/**
* Get a column from an array of arguments.
*
* @since 1.0.0
*
* @param array $args Arguments to get a column by.
* @param string $field Field to get from a column.
* @param mixed $default Default to use if no field is set.
* @return mixed Column object, or false
*/
private function get_column_field( $args = array(), $field = '', $default = false ) {
// Get the column
$column = $this->get_column_by( $args );
// Return field, or default
return isset( $column->{$field} )
? $column->{$field}
: $default;
}
/**
* Get a column from an array of arguments.
*
* @since 1.0.0
*
* @param array $args Arguments to get a column by.
* @return mixed Column object, or false
*/
private function get_column_by( $args = array() ) {
// Filter columns
$filter = $this->get_columns( $args );
// Return column or false
return ! empty( $filter )
? reset( $filter )
: false;
}
/**
* Get columns from an array of arguments.
*
* @since 1.0.0
*
* @param array $args Arguments to filter columns by.
* @param string $operator Optional. The logical operation to perform.
* @param string $field Optional. A field from the object to place
* instead of the entire object. Default false.
* @return array Array of column.
*/
private function get_columns( $args = array(), $operator = 'and', $field = false ) {
// Filter columns
$filter = wp_filter_object_list( $this->columns, $args, $operator, $field );
// Return column or false
return ! empty( $filter )
? array_values( $filter )
: array();
}
/**
* Get a single database row by any column and value, skipping cache.
*
* @since 1.0.0
*
* @param string $column_name Name of database column
* @param string $column_value Value to query for
* @return object|false False if empty/error, Object if successful
*/
private function get_item_raw( $column_name = '', $column_value = '' ) {
// Bail if no name or value
if ( empty( $column_name ) || empty( $column_value ) ) {
return false;
}
// Bail if values aren't query'able
if ( ! is_string( $column_name ) || ! is_scalar( $column_value ) ) {
return false;
}
// Get query parts
$table = $this->get_table_name();
$pattern = $this->get_column_field( array( 'name' => $column_name ), 'pattern', '%s' );
// Query database
$query = "SELECT * FROM {$table} WHERE {$column_name} = {$pattern} LIMIT 1";
$select = $this->get_db()->prepare( $query, $column_value );
$result = $this->get_db()->get_row( $select );
// Bail on failure
if ( ! $this->is_success( $result ) ) {
return false;
}
// Return row
return $result;
}
/**
* Retrieves a list of items matching the query vars.
*
* @since 1.0.0
*
* @return array|int List of items, or number of items when 'count' is passed as a query var.
*/
private function get_items() {
/**
* Fires before object items are retrieved.
*
* @since 1.0.0
*
* @param Query &$this Current instance of Query, passed by reference.
*/
do_action_ref_array( $this->apply_prefix( "pre_get_{$this->item_name_plural}" ), array( &$this ) );
// Never limit, never update item/meta caches when counting
if ( ! empty( $this->query_vars['count'] ) ) {
$this->query_vars['number'] = false;
$this->query_vars['no_found_rows'] = true;
$this->query_vars['update_item_cache'] = false;
$this->query_vars['update_meta_cache'] = false;
}
// Check the cache
$cache_key = $this->get_cache_key();
$cache_value = $this->cache_get( $cache_key, $this->cache_group );
// No cache value
if ( false === $cache_value ) {
$item_ids = $this->get_item_ids();
// Set the number of found items
$this->set_found_items( $item_ids );
// Format the cached value
$cache_value = array(
'item_ids' => $item_ids,
'found_items' => intval( $this->found_items ),
);
// Add value to the cache
$this->cache_add( $cache_key, $cache_value, $this->cache_group );
// Value exists in cache
} else {
$item_ids = $cache_value['item_ids'];
$this->found_items = intval( $cache_value['found_items'] );
}
// Pagination
if ( ! empty( $this->found_items ) && ! empty( $this->query_vars['number'] ) ) {
$this->max_num_pages = ceil( $this->found_items / $this->query_vars['number'] );
}
// Cast to int if not grouping counts
if ( ! empty( $this->query_vars['count'] ) && empty( $this->query_vars['groupby'] ) ) {
$item_ids = intval( $item_ids );
}
// Set items from IDs
$this->set_items( $item_ids );
// Return array of items
return $this->items;
}
/**
* Used internally to get a list of item IDs matching the query vars.
*
* @since 1.0.0
*
* @return int|array A single count of item IDs if a count query. An array
* of item IDs if a full query.
*/
private function get_item_ids() {
// Setup primary column, and parse the where clause
$this->parse_where();
// Order & Order By
$order = $this->parse_order( $this->query_vars['order'] );
$orderby = $this->get_order_by( $order );
// Limit & Offset
$limit = absint( $this->query_vars['number'] );
$offset = absint( $this->query_vars['offset'] );
// Limits
if ( ! empty( $limit ) ) {
$limits = ! empty( $offset )
? "LIMIT {$offset}, {$limit}"
: "LIMIT {$limit}";
} else {
$limits = '';
}
// Where & Join
$where = implode( ' AND ', $this->query_clauses['where'] );
$join = implode( ', ', $this->query_clauses['join'] );
// Group by
$groupby = $this->parse_groupby( $this->query_vars['groupby'] );
// Fields
$fields = $this->parse_fields( $this->query_vars['fields'] );
// Setup the query array (compact() is too opaque here)
$query = array(
'fields' => $fields,
'join' => $join,
'where' => $where,
'orderby' => $orderby,
'limits' => $limits,
'groupby' => $groupby
);
/**
* Filters the item query clauses.
*
* @since 1.0.0
*
* @param array $pieces A compacted array of item query clauses.
* @param Query &$this Current instance passed by reference.
*/
$clauses = (array) apply_filters_ref_array( $this->apply_prefix( "{$this->item_name_plural}_query_clauses" ), array( $query, &$this ) );
// Setup request
$this->set_request_clauses( $clauses );
$this->set_request();
// Return count