/var/www/html_us/wp-content/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableQuery.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
<?php
// phpcs:disable Generic.Commenting.Todo.TaskFound
/**
 * OrdersTableQuery class file.
 */

namespace Automattic\WooCommerce\Internal\DataStores\Orders;

use 
Automattic\WooCommerce\Internal\Utilities\DatabaseUtil;

defined'ABSPATH' ) || exit;

/**
 * This class provides a `WP_Query`-like interface to custom order tables.
 *
 * @property-read int   $found_orders  Number of found orders.
 * @property-read int   $found_posts   Alias of the `$found_orders` property.
 * @property-read int   $max_num_pages Max number of pages matching the current query.
 * @property-read array $orders        Order objects, or order IDs.
 * @property-read array $posts         Alias of the $orders property.
 */
class OrdersTableQuery {

    
/**
     * Values to ignore when parsing query arguments.
     */
    
public const SKIPPED_VALUES = array( '', array(), null );

    
/**
     * Regex used to catch "shorthand" comparisons in date-related query args.
     */
    
public const REGEX_SHORTHAND_DATES '/([^.<>]*)(>=|<=|>|<|\.\.\.)([^.<>]+)/';

    
/**
     * Highest possible unsigned bigint value (unsigned bigints being the type of the `id` column).
     *
     * This is deliberately held as a string, rather than a numeric type, for inclusion within queries.
     */
    
private const MYSQL_MAX_UNSIGNED_BIGINT '18446744073709551615';

    
/**
     * Names of all COT tables (orders, addresses, operational_data, meta) in the form 'table_id' => 'table name'.
     *
     * @var array
     */
    
private $tables = array();

    
/**
     * Column mappings for all COT tables.
     *
     * @var array
     */
    
private $mappings = array();

    
/**
     * Query vars after processing and sanitization.
     *
     * @var array
     */
    
private $args = array();

    
/**
     * Columns to be selected in the SELECT clause.
     *
     * @var array
     */
    
private $fields = array();

    
/**
     * Array of table aliases and conditions used to compute the JOIN clause of the query.
     *
     * @var array
     */
    
private $join = array();

    
/**
     * Array of fields and conditions used to compute the WHERE clause of the query.
     *
     * @var array
     */
    
private $where = array();

    
/**
     * Field to be used in the GROUP BY clause of the query.
     *
     * @var array
     */
    
private $groupby = array();

    
/**
     * Array of fields used to compute the ORDER BY clause of the query.
     *
     * @var array
     */
    
private $orderby = array();

    
/**
     * Limits used to compute the LIMIT clause of the query.
     *
     * @var array
     */
    
private $limits = array();

    
/**
     * Results (order IDs) for the current query.
     *
     * @var array
     */
    
private $orders = array();

    
/**
     * Final SQL query to run after processing of args.
     *
     * @var string
     */
    
private $sql '';

    
/**
     * Final SQL query to count results after processing of args.
     *
     * @var string
     */
    
private $count_sql '';

    
/**
     * The number of pages (when pagination is enabled).
     *
     * @var int
     */
    
private $max_num_pages 0;

    
/**
     * The number of orders found.
     *
     * @var int
     */
    
private $found_orders 0;

    
/**
     * Field query parser.
     *
     * @var OrdersTableFieldQuery
     */
    
private $field_query null;

    
/**
     * Meta query parser.
     *
     * @var OrdersTableMetaQuery
     */
    
private $meta_query null;

    
/**
     * Search query parser.
     *
     * @var OrdersTableSearchQuery?
     */
    
private $search_query null;

    
/**
     * Date query parser.
     *
     * @var WP_Date_Query
     */
    
private $date_query null;

    
/**
     * Instance of the OrdersTableDataStore class.
     *
     * @var OrdersTableDataStore
     */
    
private $order_datastore null;

    
/**
     * Whether to run filters to modify the query or not.
     *
     * @var boolean
     */
    
private $suppress_filters false;

    
/**
     * Sets up and runs the query after processing arguments.
     *
     * @param array $args Array of query vars.
     */
    
public function __construct$args = array() ) {
        
// Note that ideally we would inject this dependency via constructor, but that's not possible since this class needs to be backward compatible with WC_Order_Query class.
        
$this->order_datastore wc_get_container()->getOrdersTableDataStore::class );

        
$this->tables   $this->order_datastore::get_all_table_names_with_id();
        
$this->mappings $this->order_datastore->get_all_order_column_mappings();

        
$this->suppress_filters array_key_exists'suppress_filters'$args ) ? (bool) $args['suppress_filters'] : false;
        unset( 
$args['suppress_filters'] );

        
$this->args $args;

        
// TODO: args to be implemented.
        
unset( $this->args['customer_note'], $this->args['name'] );

        
$this->build_query();
        if ( ! 
$this->maybe_override_query() ) {
            
$this->run_query();
        }
    }

    
/**
     * Lets the `woocommerce_hpos_pre_query` filter override the query.
     *
     * @return boolean Whether the query was overridden or not.
     */
    
private function maybe_override_query(): bool {
        
/**
         * Filters the orders array before the query takes place.
         *
         * Return a non-null value to bypass the HPOS default order queries.
         *
         * If the query includes limits via the `limit`, `page`, or `offset` arguments, we
         * encourage the `found_orders` and `max_num_pages` properties to also be set.
         *
         * @since 8.2.0
         *
         * @param array|null $order_data {
         *     An array of order data.
         *     @type int[] $orders        Return an array of order IDs data to short-circuit the HPOS query,
         *                                or null to allow HPOS to run its normal query.
         *     @type int   $found_orders  The number of orders found.
         *     @type int   $max_num_pages The number of pages.
         * }
         * @param OrdersTableQuery   $query The OrdersTableQuery instance.
         * @param string             $sql The OrdersTableQuery instance.
         */
        
$pre_query apply_filters'woocommerce_hpos_pre_query'null$this$this->sql );
        if ( ! 
$pre_query || ! isset( $pre_query[0] ) || ! is_array$pre_query[0] ) ) {
            return 
false;
        }

        
// If the filter set the orders, make sure the others values are set as well and skip running the query.
        
list( $this->orders$this->found_orders$this->max_num_pages ) = $pre_query;

        if ( ! 
is_int$this->found_orders ) || $this->found_orders ) {
            
$this->found_orders count$this->orders );
        }

        if ( ! 
is_int$this->max_num_pages ) || $this->max_num_pages ) {
            if ( ! 
$this->arg_isset'limit' ) || ! is_int$this->args['limit'] ) || $this->args['limit'] < ) {
                
$this->args['limit'] = 10;
            }
            
$this->max_num_pages = (int) ceil$this->found_orders $this->args['limit'] );
        }

        return 
true;
    }

    
/**
     * Remaps some legacy and `WP_Query` specific query vars to vars available in the customer order table scheme.
     *
     * @return void
     */
    
private function maybe_remap_args(): void {
        
$mapping = array(
            
// WP_Query legacy.
            
'post_date'           => 'date_created',
            
'post_date_gmt'       => 'date_created_gmt',
            
'post_modified'       => 'date_updated',
            
'post_modified_gmt'   => 'date_updated_gmt',
            
'post_status'         => 'status',
            
'_date_completed'     => 'date_completed',
            
'_date_paid'          => 'date_paid',
            
'paged'               => 'page',
            
'post_parent'         => 'parent_order_id',
            
'post_parent__in'     => 'parent_order_id',
            
'post_parent__not_in' => 'parent_exclude',
            
'post__not_in'        => 'exclude',
            
'posts_per_page'      => 'limit',
            
'p'                   => 'id',
            
'post__in'            => 'id',
            
'post_type'           => 'type',
            
'fields'              => 'return',

            
'customer_user'       => 'customer_id',
            
'order_currency'      => 'currency',
            
'order_version'       => 'woocommerce_version',
            
'cart_discount'       => 'discount_total_amount',
            
'cart_discount_tax'   => 'discount_tax_amount',
            
'order_shipping'      => 'shipping_total_amount',
            
'order_shipping_tax'  => 'shipping_tax_amount',
            
'order_tax'           => 'tax_amount',

            
// Translate from WC_Order_Query to table structure.
            
'version'             => 'woocommerce_version',
            
'date_modified'       => 'date_updated',
            
'date_modified_gmt'   => 'date_updated_gmt',
            
'discount_total'      => 'discount_total_amount',
            
'discount_tax'        => 'discount_tax_amount',
            
'shipping_total'      => 'shipping_total_amount',
            
'shipping_tax'        => 'shipping_tax_amount',
            
'cart_tax'            => 'tax_amount',
            
'total'               => 'total_amount',
            
'customer_ip_address' => 'ip_address',
            
'customer_user_agent' => 'user_agent',
            
'parent'              => 'parent_order_id',
        );

        foreach ( 
$mapping as $query_key => $table_field ) {
            if ( isset( 
$this->args$query_key ] ) && '' !== $this->args$query_key ] ) {
                
$this->args$table_field ] = $this->args$query_key ];
                unset( 
$this->args$query_key ] );
            }
        }

        
// meta_query.
        
$this->args['meta_query'] = ( $this->arg_isset'meta_query' ) && is_array$this->args['meta_query'] ) ) ? $this->args['meta_query'] : array(); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query

        
$shortcut_meta_query = array();
        foreach ( array( 
'key''value''compare''type''compare_key''type_key' ) as $key ) {
            if ( 
$this->arg_isset"meta_{$key}) ) {
                
$shortcut_meta_query$key ] = $this->args"meta_{$key}];
            }
        }

        if ( ! empty( 
$shortcut_meta_query ) ) {
            if ( ! empty( 
$this->args['meta_query'] ) ) {
                
$this->args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                    
'relation' => 'AND',
                    
$shortcut_meta_query,
                    
$this->args['meta_query'],
                );
            } else {
                
$this->args['meta_query'] = array( $shortcut_meta_query ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
            
}
        }
    }

    
/**
     * Generates a `WP_Date_Query` compatible query from a given date.
     * YYYY-MM-DD queries have 'day' precision for backwards compatibility.
     *
     * @param mixed $date The date. Can be a {@see \WC_DateTime}, a timestamp or a string.
     * @return array An array with keys 'year', 'month', 'day' and possibly 'hour', 'minute' and 'second'.
     */
    
private function date_to_date_query_arg$date ): array {
        
$result = array(
            
'year'  => '',
            
'month' => '',
            
'day'   => '',
        );

        
$precision null;
        if ( 
is_numeric$date ) ) {
            
$date      = new \WC_DateTime"@{$date}", new \DateTimeZone'UTC' ) );
            
$precision 'second';
        } elseif ( ! 
is_a$date'WC_DateTime' ) ) {
            
// For backwards compat (see https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query#date)
            // only YYYY-MM-DD is considered for date values. Timestamps do support second precision.
            
$date      wc_string_to_datetimedate'Y-m-d'strtotime$date ) ) );
            
$precision 'day';
        }

        
$result['year']  = $date->date'Y' );
        
$result['month'] = $date->date'm' );
        
$result['day']   = $date->date'd' );

        if ( 
'second' === $precision ) {
            
$result['hour']   = $date->date'H' );
            
$result['minute'] = $date->date'i' );
            
$result['second'] = $date->date's' );
        }

        return 
$result;
    }

    
/**
     * Returns UTC-based date query arguments for a combination of local time dates and a date shorthand operator.
     *
     * @param  array  $dates_raw Array of dates (in local time) to use in combination with the operator.
     * @param  string $operator One of the operators supported by date queries (<, <=, =, ..., >, >=).
     * @return array Partial date query arg with relevant dates now UTC-based.
     *
     * @throws \Exception If an invalid date shorthand operator is specified.
     *
     * @since 8.2.0
     */
    
private function local_time_to_gmt_date_query$dates_raw$operator ) {
        
$result = array();

        
// Convert YYYY-MM-DD to UTC timestamp. Per https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query#date only date is relevant (time is ignored).
        
foreach ( $dates_raw as &$raw_date ) {
            
$raw_date is_numeric$raw_date ) ? $raw_date strtotimeget_gmt_from_datedate'Y-m-d'strtotime$raw_date ) ) ) );
        }

        
$date1 end$dates_raw );

        switch ( 
$operator ) {
            case 
'>':
                
$result = array(
                    
'after'     => $this->date_to_date_query_arg$date1 DAY_IN_SECONDS ),
                    
'inclusive' => true,
                );
                break;
            case 
'>=':
                
$result = array(
                    
'after'     => $this->date_to_date_query_arg$date1 ),
                    
'inclusive' => true,
                );
                break;
            case 
'=':
                
$result = array(
                    
'relation' => 'AND',
                    array(
                        
'after'     => $this->date_to_date_query_arg$date1 ),
                        
'inclusive' => true,
                    ),
                    array(
                        
'before'    => $this->date_to_date_query_arg$date1 DAY_IN_SECONDS ),
                        
'inclusive' => false,
                    ),
                );
                break;
            case 
'<=':
                
$result = array(
                    
'before'    => $this->date_to_date_query_arg$date1 DAY_IN_SECONDS ),
                    
'inclusive' => false,
                );
                break;
            case 
'<':
                
$result = array(
                    
'before'    => $this->date_to_date_query_arg$date1 ),
                    
'inclusive' => false,
                );
                break;
            case 
'...':
                
$result = array(
                    
'relation' => 'AND',
                    
$this->local_time_to_gmt_date_query( array( $dates_raw[1] ), '<=' ),
                    
$this->local_time_to_gmt_date_query( array( $dates_raw[0] ), '>=' ),
                );

                break;
        }

        if ( ! 
$result ) {
            throw new 
\Exception'Please specify a valid date shorthand operator.' );
        }

        return 
$result;
    }

    
/**
     * Processes date-related query args and merges the result into 'date_query'.
     *
     * @return void
     * @throws \Exception When date args are invalid.
     */
    
private function process_date_args(): void {
        if ( 
$this->arg_isset'date_query' ) ) {
            
// Process already passed date queries args.
            
$this->args['date_query'] = $this->map_gmt_and_post_keys_to_hpos_keys$this->args['date_query'] );
        }

        
$valid_operators        = array( '>''>=''=''<=''<''...' );
        
$date_queries           = array();
        
$local_to_gmt_date_keys = array(
            
'date_created'   => 'date_created_gmt',
            
'date_updated'   => 'date_updated_gmt',
            
'date_paid'      => 'date_paid_gmt',
            
'date_completed' => 'date_completed_gmt',
        );

        
$gmt_date_keys   array_values$local_to_gmt_date_keys );
        
$local_date_keys array_keys$local_to_gmt_date_keys );

        
$valid_date_keys array_merge$gmt_date_keys$local_date_keys );
        
$date_keys       array_filter$valid_date_keys, array( $this'arg_isset' ) );

        foreach ( 
$date_keys as $date_key ) {
            
$is_local   in_array$date_key$local_date_keystrue );
            
$date_value $this->args$date_key ];
            
$operator   '=';
            
$dates_raw  = array();
            
$dates      = array();

            if ( 
is_string$date_value ) && preg_matchself::REGEX_SHORTHAND_DATES$date_value$matches ) ) {
                
$operator in_array$matches[2], $valid_operatorstrue ) ? $matches[2] : '';

                if ( ! empty( 
$matches[1] ) ) {
                    
$dates_raw[] = $matches[1];
                }

                
$dates_raw[] = $matches[3];
            } else {
                
$dates_raw[] = $date_value;
            }

            if ( empty( 
$dates_raw ) || ! $operator || ( '...' === $operator && count$dates_raw ) < ) ) {
                throw new 
\Exception'Invalid date_query' );
            }

            if ( 
$is_local ) {
                
$date_key $local_to_gmt_date_keys$date_key ];

                if ( ! 
is_numeric$dates_raw[0] ) && ( ! isset( $dates_raw[1] ) || ! is_numeric$dates_raw[1] ) ) ) {
                    
// Only non-numeric args can be considered local time. Timestamps are assumed to be UTC per https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query#date.
                    
$date_queries[] = array_merge(
                        array(
                            
'column' => $date_key,
                        ),
                        
$this->local_time_to_gmt_date_query$dates_raw$operator )
                    );

                    continue;
                }
            }

            
$operator_to_keys = array();

            if ( 
in_array$operator, array( '>''>=''...' ), true ) ) {
                
$operator_to_keys[] = 'after';
            }

            if ( 
in_array$operator, array( '<''<=''...' ), true ) ) {
                
$operator_to_keys[] = 'before';
            }

            
$dates          array_map( array( $this'date_to_date_query_arg' ), $dates_raw );
            
$date_queries[] = array_merge(
                array(
                    
'column'    => $date_key,
                    
'inclusive' => ! in_array$operator, array( '<''>' ), true ),
                ),
                
'=' === $operator
                    
end$dates )
                    : 
array_combine$operator_to_keys$dates )
            );
        }

        
// Add top-level date parameters to the date_query.
        
$tl_query = array();
        foreach ( array( 
'hour''minute''second''year''monthnum''week''day''year' ) as $tl_key ) {
            if ( 
$this->arg_isset$tl_key ) ) {
                
$tl_query$tl_key ] = $this->args$tl_key ];
                unset( 
$this->args$tl_key ] );
            }
        }

        if ( 
$tl_query ) {
            
$tl_query['column'] = 'date_created_gmt';
            
$date_queries[]     = $tl_query;
        }

        if ( 
$date_queries ) {
            if ( ! 
$this->arg_isset'date_query' ) ) {
                
$this->args['date_query'] = array();
            }

            
$this->args['date_query'] = array_merge(
                array( 
'relation' => 'AND' ),
                
$date_queries,
                
$this->args['date_query']
            );
        }

        
$this->process_date_query_columns();
    }

    
/**
     * Helper function to map posts and gmt based keys to HPOS keys.
     *
     * @param array $query Date query argument.
     *
     * @return array|mixed Date query argument with modified keys.
     */
    
private function map_gmt_and_post_keys_to_hpos_keys$query ) {
        if ( ! 
is_array$query ) ) {
            return 
$query;
        }

        
$post_to_hpos_mappings = array(
            
'post_date'         => 'date_created',
            
'post_date_gmt'     => 'date_created_gmt',
            
'post_modified'     => 'date_updated',
            
'post_modified_gmt' => 'date_updated_gmt',
            
'_date_completed'   => 'date_completed',
            
'_date_paid'        => 'date_paid',
            
'date_modified'     => 'date_updated',
            
'date_modified_gmt' => 'date_updated_gmt',
        );

        
$local_to_gmt_date_keys = array(
            
'date_created'   => 'date_created_gmt',
            
'date_updated'   => 'date_updated_gmt',
            
'date_paid'      => 'date_paid_gmt',
            
'date_completed' => 'date_completed_gmt',
        );

        
array_walk(
            
$query,
            function ( &
$sub_query ) {
                
$sub_query $this->map_gmt_and_post_keys_to_hpos_keys$sub_query );
            }
        );

        if ( ! isset( 
$query['column'] ) ) {
            return 
$query;
        }

        if ( isset( 
$post_to_hpos_mappings$query['column'] ] ) ) {
            
$query['column'] = $post_to_hpos_mappings$query['column'] ];
        }

        
// Convert any local dates to GMT.
        
if ( isset( $local_to_gmt_date_keys$query['column'] ] ) ) {
            
$query['column']  = $local_to_gmt_date_keys$query['column'] ];
            
$op               = isset( $query['after'] ) ? 'after' 'before';
            
$date_value_local $query$op ];
            
$date_value_gmt   wc_string_to_timestampget_gmt_from_datewc_string_to_datetime$date_value_local ) ) );
            
$query$op ]     = $this->date_to_date_query_arg$date_value_gmt );
        }

        return 
$query;
    }

    
/**
     * Makes sure all 'date_query' columns are correctly prefixed and their respective tables are being JOIN'ed.
     *
     * @return void
     */
    
private function process_date_query_columns() {
        global 
$wpdb;

        
$legacy_columns = array(
            
'post_date'         => 'date_created_gmt',
            
'post_date_gmt'     => 'date_created_gmt',
            
'post_modified'     => 'date_modified_gmt',
            
'post_modified_gmt' => 'date_updated_gmt',
        );
        
$table_mapping  = array(
            
'date_created_gmt'   => $this->tables['orders'],
            
'date_updated_gmt'   => $this->tables['orders'],
            
'date_paid_gmt'      => $this->tables['operational_data'],
            
'date_completed_gmt' => $this->tables['operational_data'],
        );

        if ( empty( 
$this->args['date_query'] ) ) {
            return;
        }

        
array_walk_recursive(
            
$this->args['date_query'],
            function ( &
$value$key ) use ( $legacy_columns$table_mapping$wpdb ) {
                if ( 
'column' !== $key ) {
                    return;
                }

                
// Translate legacy columns from wp_posts if necessary.
                
$value =
                    ( isset( 
$legacy_columns$value ] ) || isset( $legacy_columns"{$wpdb->posts}.{$value}] ) )
                    ? 
$legacy_columns$value ]
                    : 
$value;

                
$table $table_mapping$value ] ?? null;

                if ( ! 
$table ) {
                    return;
                }

                
$value "{$table}.{$value}";

                if ( 
$table !== $this->tables['orders'] ) {
                    
$this->join$table'''''inner'true );
                }
            }
        );
    }

    
/**
     * Sanitizes the 'status' query var.
     *
     * @return void
     */
    
private function sanitize_status(): void {
        
// Sanitize status.
        
$valid_statuses array_keyswc_get_order_statuses() );

        if ( empty( 
$this->args['status'] ) || 'any' === $this->args['status'] ) {
            
$this->args['status'] = $valid_statuses;
        } elseif ( 
'all' === $this->args['status'] ) {
            
$this->args['status'] = array();
        } else {
            
$this->args['status'] = is_array$this->args['status'] ) ? $this->args['status'] : array( $this->args['status'] );

            foreach ( 
$this->args['status'] as &$status ) {
                
$status in_array'wc-' $status$valid_statusestrue ) ? 'wc-' $status $status;
            }

            
$this->args['status'] = array_uniquearray_filter$this->args['status'] ) );
        }
    }

    
/**
     * Parses and sanitizes the 'orderby' query var.
     *
     * @return void
     */
    
private function sanitize_order_orderby(): void {
        
// Allowed keys.
        // TODO: rand, meta keys, etc.
        
$allowed_keys = array( 'ID''id''type''date''modified''parent' );

        
// Translate $orderby to a valid field.
        
$mapping = array(
            
'ID'            => "{$this->tables['orders']}.id",
            
'id'            => "{$this->tables['orders']}.id",
            
'type'          => "{$this->tables['orders']}.type",
            
'date'          => "{$this->tables['orders']}.date_created_gmt",
            
'date_created'  => "{$this->tables['orders']}.date_created_gmt",
            
'modified'      => "{$this->tables['orders']}.date_updated_gmt",
            
'date_modified' => "{$this->tables['orders']}.date_updated_gmt",
            
'parent'        => "{$this->tables['orders']}.parent_order_id",
            
'total'         => "{$this->tables['orders']}.total_amount",
            
'order_total'   => "{$this->tables['orders']}.total_amount",
        );

        
$order   $this->args['order'] ?? '';
        
$orderby $this->args['orderby'] ?? '';

        if ( 
'none' === $orderby ) {
            return;
        }

        
// No need to sanitize, will be processed in calling function.
        
if ( 'include' === $orderby || 'post__in' === $orderby ) {
            return;
        }

        if ( 
is_string$orderby ) ) {
            
$orderby_fields array_map'trim'explode' '$orderby ) );
            
$orderby        = array();
            foreach ( 
$orderby_fields as $field ) {
                
$orderby$field ] = $order;
            }
        }

        
$allowed_orderby array_merge(
            
array_keys$mapping ),
            
array_values$mapping ),
            
$this->meta_query $this->meta_query->get_orderby_keys() : array()
        );

        
$this->args['orderby'] = array();
        foreach ( 
$orderby as $order_key => $order ) {
            if ( ! 
in_array$order_key$allowed_orderbytrue ) ) {
                continue;
            }

            if ( isset( 
$mapping$order_key ] ) ) {
                
$order_key $mapping$order_key ];
            }

            
$this->args['orderby'][ $order_key ] = $this->sanitize_order$order );
        }
    }

    
/**
     * Makes sure the order in an ORDER BY statement is either 'ASC' o 'DESC'.
     *
     * @param string $order The unsanitized order.
     * @return string The sanitized order.
     */
    
private function sanitize_orderstring $order ): string {
        
$order strtoupper$order );

        return 
in_array$order, array( 'ASC''DESC' ), true ) ? $order 'DESC';
    }

    
/**
     * Builds the final SQL query to be run.
     *
     * @return void
     */
    
private function build_query(): void {
        
$this->maybe_remap_args();

        
// Field queries.
        
if ( ! empty( $this->args['field_query'] ) ) {
            
$this->field_query = new OrdersTableFieldQuery$this );
            
$sql               $this->field_query->get_sql_clauses();
            
$this->join        $sql['join'] ? array_merge$this->join$sql['join'] ) : $this->join;
            
$this->where       $sql['where'] ? array_merge$this->where$sql['where'] ) : $this->where;
        }

        
// Build query.
        
$this->process_date_args();
        
$this->process_orders_table_query_args();
        
$this->process_operational_data_table_query_args();
        
$this->process_addresses_table_query_args();

        
// Search queries.
        
if ( ! empty( $this->args['s'] ) ) {
            
$this->search_query = new OrdersTableSearchQuery$this );
            
$sql                $this->search_query->get_sql_clauses();
            
$this->join         $sql['join'] ? array_merge$this->join$sql['join'] ) : $this->join;
            
$this->where        $sql['where'] ? array_merge$this->where$sql['where'] ) : $this->where;
        }

        
// Meta queries.
        
if ( ! empty( $this->args['meta_query'] ) ) {
            
$this->meta_query = new OrdersTableMetaQuery$this );

            
$sql $this->meta_query->get_sql_clauses();

            
$this->join  $sql['join'] ? array_merge$this->join$sql['join'] ) : $this->join;
            
$this->where $sql['where'] ? array_merge$this->where, array( $sql['where'] ) ) : $this->where;

        }

        
// Date queries.
        
if ( ! empty( $this->args['date_query'] ) ) {
            
$this->date_query = new \WP_Date_Query$this->args['date_query'], "{$this->tables['orders']}.date_created_gmt" );
            
$this->where[]    = substrtrim$this->date_query->get_sql() ), ); // WP_Date_Query includes "AND".
        
}

        
$this->process_orderby();
        
$this->process_limit();

        
$orders_table $this->tables['orders'];

        
// Group by is a faster substitute for DISTINCT, as long as we are only selecting IDs. MySQL don't like it when we join tables and use DISTINCT.
        
$this->groupby[] = "{$this->tables['orders']}.id";
        
$this->fields    "{$orders_table}.id";
        
$fields          $this->fields;

        
// JOIN.
        
$join implode' 'array_uniquearray_filterarray_map'trim'$this->join ) ) ) );

        
// WHERE.
        
$where '1=1';
        foreach ( 
$this->where as $_where ) {
            if ( 
strlen$_where ) > ) {
                
$where .= " AND ({$_where})";
            }
        }

        
// ORDER BY.
        
$orderby $this->orderby implode', '$this->orderby ) : '';

        
// LIMITS.
        
$limits '';

        if ( ! empty( 
$this->limits ) && count$this->limits ) === ) {
            list( 
$offset$row_count ) = $this->limits;
            
$row_count                  = -=== $row_count self::MYSQL_MAX_UNSIGNED_BIGINT : (int) $row_count;
            
$limits                     'LIMIT ' . (int) $offset ', ' $row_count;
        }

        
// GROUP BY.
        
$groupby $this->groupby implode', ', (array) $this->groupby ) : '';

        
$pieces compact'fields''join''where''groupby''orderby''limits' );

        if ( ! 
$this->suppress_filters ) {
            
/**
             * Filters all query clauses at once.
             * Covers the fields (SELECT), JOIN, WHERE, GROUP BY, ORDER BY, and LIMIT clauses.
             *
             * @since 7.9.0
             *
             * @param string[]         $clauses {
             *     Associative array of the clauses for the query.
             *
             *     @type string $fields  The SELECT clause of the query.
             *     @type string $join    The JOIN clause of the query.
             *     @type string $where   The WHERE clause of the query.
             *     @type string $groupby The GROUP BY clause of the query.
             *     @type string $orderby The ORDER BY clause of the query.
             *     @type string $limits  The LIMIT clause of the query.
             * }
             * @param OrdersTableQuery $query   The OrdersTableQuery instance (passed by reference).
             * @param array            $args    Query args.
             */
            
$clauses = (array) apply_filters_ref_array'woocommerce_orders_table_query_clauses', array( $pieces, &$this$this->args ) );

            
$fields  $clauses['fields'] ?? '';
            
$join    $clauses['join'] ?? '';
            
$where   $clauses['where'] ?? '';
            
$groupby $clauses['groupby'] ?? '';
            
$orderby $clauses['orderby'] ?? '';
            
$limits  $clauses['limits'] ?? '';
        }

        
$groupby $groupby ? ( 'GROUP BY ' $groupby ) : '';
        
$orderby $orderby ? ( 'ORDER BY ' $orderby ) : '';

        
$this->sql "SELECT $fields FROM $orders_table $join WHERE $where $groupby $orderby $limits";

        if ( ! 
$this->suppress_filters ) {
            
/**
             * Filters the completed SQL query.
             *
             * @since 7.9.0
             *
             * @param string           $sql   The complete SQL query.
             * @param OrdersTableQuery $query The OrdersTableQuery instance (passed by reference).
             * @param array            $args  Query args.
             */
            
$this->sql apply_filters_ref_array'woocommerce_orders_table_query_sql', array( $this->sql, &$this$this->args ) );
        }

        
$this->build_count_query$fields$join$where$groupby );
    }

    
/**
     * Build SQL query for counting total number of results.
     *
     * @param string $fields Prepared fields for SELECT clause.
     * @param string $join Prepared JOIN clause.
     * @param string $where Prepared WHERE clause.
     * @param string $groupby Prepared GROUP BY clause.
     */
    
private function build_count_query$fields$join$where$groupby ) {
        if ( ! isset( 
$this->sql ) || '' === $this->sql ) {
            
wc_doing_it_wrong__FUNCTION__'Count query can only be build after main query is built.''7.3.0' );
        }
        
$orders_table $this->tables['orders'];
        
$count_fields "COUNT(DISTINCT $fields)";
        if ( 
"{$orders_table}.id" === $fields && '' === $join ) {
            
// DISTINCT adds performance overhead, exclude the DISTINCT function when confident it is not needed.
            
$count_fields 'COUNT(*)';
        }
        
$this->count_sql "SELECT $count_fields FROM $orders_table $join WHERE $where";

        if ( ! 
$this->suppress_filters ) {
            
/**
             * Filters the count SQL query.
             *
             * @since 8.6.0
             *
             * @param string           $sql   The count SQL query.
             * @param OrdersTableQuery $query The OrdersTableQuery instance (passed by reference).
             * @param array            $args  Query args.
             * @param string           $fields Prepared fields for SELECT clause.
             * @param string           $join Prepared JOIN clause.
             * @param string           $where Prepared WHERE clause.
             * @param string           $groupby Prepared GROUP BY clause.
             */
            
$this->count_sql apply_filters_ref_array'woocommerce_orders_table_query_count_sql', array( $this->count_sql, &$this$this->args$fields$join$where$groupby ) );
        }
    }

    
/**
     * Returns the table alias for a given table mapping.
     *
     * @param string $mapping_id The mapping name (e.g. 'orders' or 'operational_data').
     * @return string Table alias.
     *
     * @since 7.0.0
     */
    
public function get_core_mapping_aliasstring $mapping_id ): string {
        return 
in_array$mapping_id, array( 'billing_address''shipping_address' ), true )
            ? 
$mapping_id
            
$this->tables$mapping_id ];
    }

    
/**
     * Returns an SQL JOIN clause that can be used to join the main orders table with another order table.
     *
     * @param string $mapping_id The mapping name (e.g. 'orders' or 'operational_data').
     * @return string The JOIN clause.
     *
     * @since 7.0.0
     */
    
public function get_core_mapping_joinstring $mapping_id ): string {
        global 
$wpdb;

        if ( 
'orders' === $mapping_id ) {
            return 
'';
        }

        
$is_address_mapping in_array$mapping_id, array( 'billing_address''shipping_address' ), true );

        
$alias   $this->get_core_mapping_alias$mapping_id );
        
$table   $is_address_mapping $this->tables['addresses'] : $this->tables$mapping_id ];
        
$join    '';
        
$join_on '';

        
$join .= "INNER JOIN `{$table}`" . ( $alias !== $table " AS `{$alias}`" '' );

        if ( isset( 
$this->mappings$mapping_id ]['order_id'] ) ) {
            
$join_on .= "`{$this->tables['orders']}`.id = `{$alias}`.order_id";
        }

        if ( 
$is_address_mapping ) {
            
$join_on .= $wpdb->prepare" AND `{$alias}`.address_type = %s"substr$mapping_id0, -) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
}

        return 
$join . ( $join_on " ON ( {$join_on} )" '' );
    }

    
/**
     * JOINs the main orders table with another table.
     *
     * @param string  $table      Table name (including prefix).
     * @param string  $alias      Table alias to use. Defaults to $table.
     * @param string  $on         ON clause. Defaults to "wc_orders.id = {$alias}.order_id".
     * @param string  $join_type  JOIN type: LEFT, RIGHT or INNER.
     * @param boolean $alias_once If TRUE, table won't be JOIN'ed again if already JOIN'ed.
     * @return void
     * @throws \Exception When an error occurs, such as trying to re-use an alias with $alias_once = FALSE.
     */
    
private function joinstring $tablestring $alias ''string $on ''string $join_type 'inner'bool $alias_once false ) {
        
$alias     = empty( $alias ) ? $table $alias;
        
$join_type strtouppertrim$join_type ) );

        if ( 
$this->tables['orders'] === $alias ) {
            
// translators: %s is a table name.
            
throw new \Exceptionsprintf__'%s can not be used as a table alias in OrdersTableQuery''woocommerce' ), $alias ) );
        }

        if ( empty( 
$on ) ) {
            if ( 
$this->tables['orders'] === $table ) {
                
$on "`{$this->tables['orders']}`.id = `{$alias}`.id";
            } else {
                
$on "`{$this->tables['orders']}`.id = `{$alias}`.order_id";
            }
        }

        if ( isset( 
$this->join$alias ] ) ) {
            if ( ! 
$alias_once ) {
                
// translators: %s is a table name.
                
throw new \Exceptionsprintf__'Can not re-use table alias "%s" in OrdersTableQuery.''woocommerce' ), $alias ) );
            }

            return;
        }

        if ( 
'' === $join_type || ! in_array$join_type, array( 'LEFT''RIGHT''INNER' ), true ) ) {
            
$join_type 'INNER';
        }

        
$sql_join  '';
        
$sql_join .= "{$join_type} JOIN `{$table}` ";
        
$sql_join .= ( $alias !== $table ) ? "AS `{$alias}` " '';
        
$sql_join .= "ON ( {$on} )";

        
$this->join$alias ] = $sql_join;
    }

    
/**
     * Generates a properly escaped and sanitized WHERE condition for a given field.
     *
     * @param string $table    The table the field belongs to.
     * @param string $field    The field or column name.
     * @param string $operator The operator to use in the condition. Defaults to '=' or 'IN' depending on $value.
     * @param mixed  $value    The value.
     * @param string $type     The column type as specified in {@see OrdersTableDataStore} column mappings.
     * @return string The resulting WHERE condition.
     */
    
public function wherestring $tablestring $fieldstring $operator$valuestring $type ): string {
        global 
$wpdb;

        
$db_util  wc_get_container()->getDatabaseUtil::class );
        
$operator strtoupper'' !== $operator $operator '=' );

        try {
            
$format $db_util->get_wpdb_format_for_type$type );
        } catch ( 
\Exception $e ) {
            
$format '%s';
        }

        
// = and != can be shorthands for IN and NOT in for array values.
        
if ( is_array$value ) && '=' === $operator ) {
            
$operator 'IN';
        } elseif ( 
is_array$value ) && '!=' === $operator ) {
            
$operator 'NOT IN';
        }

        if ( ! 
in_array$operator, array( '=''!=''IN''NOT IN' ), true ) ) {
            return 
false;
        }

        if ( 
is_array$value ) ) {
            
$value array_map( array( $db_util'format_object_value_for_db' ), $valuearray_fill0count$value ), $type ) );
        } else {
            
$value $db_util->format_object_value_for_db$value$type );
        }

        if ( 
is_array$value ) ) {
            
$placeholder array_fill0count$value ), $format );
            
$placeholder '(' implode','$placeholder ) . ')';
        } else {
            
$placeholder $format;
        }

        
$sql $wpdb->prepare"{$table}.{$field} {$operator} {$placeholder}"$value ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare

        
return $sql;
    }

    
/**
     * Processes fields related to the orders table.
     *
     * @return void
     */
    
private function process_orders_table_query_args(): void {
        
$this->sanitize_status();

        
$fields array_filter(
            array(
                
'id',
                
'status',
                
'type',
                
'currency',
                
'tax_amount',
                
'customer_id',
                
'billing_email',
                
'total_amount',
                
'parent_order_id',
                
'payment_method',
                
'payment_method_title',
                
'transaction_id',
                
'ip_address',
                
'user_agent',
            ),
            array( 
$this'arg_isset' )
        );

        foreach ( 
$fields as $arg_key ) {
            
$this->where[] = $this->where$this->tables['orders'], $arg_key'='$this->args$arg_key ], $this->mappings['orders'][ $arg_key ]['type'] );
        }

        if ( 
$this->arg_isset'parent_exclude' ) ) {
            
$this->where[] = $this->where$this->tables['orders'], 'parent_order_id''!='$this->args['parent_exclude'], 'int' );
        }

        if ( 
$this->arg_isset'exclude' ) ) {
            
$this->where[] = $this->where$this->tables['orders'], 'id''!='$this->args['exclude'], 'int' );
        }

        
// 'customer' is a very special field.
        
if ( $this->arg_isset'customer' ) ) {
            
$customer_query $this->generate_customer_query$this->args['customer'] );

            if ( 
$customer_query ) {
                
$this->where[] = $customer_query;
            }
        }
    }

    
/**
     * Generate SQL conditions for the 'customer' query.
     *
     * @param array  $values   List of customer ids or emails.
     * @param string $relation 'OR' or 'AND' relation used to build the customer query.
     * @return string SQL to be used in a WHERE clause.
     */
    
private function generate_customer_query$valuesstring $relation 'OR' ): string {
        
$values is_array$values ) ? $values : array( $values );
        
$ids    = array();
        
$emails = array();
        
$pieces = array();
        foreach ( 
$values as $value ) {
            if ( 
is_array$value ) ) {
                
$sql      $this->generate_customer_query$value'AND' );
                
$pieces[] = $sql '(' $sql ')' '';
            } elseif ( 
is_numeric$value ) ) {
                
$ids[] = absint$value );
            } elseif ( 
is_string$value ) && is_email$value ) ) {
                
$emails[] = sanitize_email$value );
            } else {
                
// Invalid query.
                
$pieces[] = '1=0';
            }
        }

        if ( 
$ids ) {
            
$pieces[] = $this->where$this->tables['orders'], 'customer_id''='$ids'int' );
        }

        if ( 
$emails ) {
            
$pieces[] = $this->where$this->tables['orders'], 'billing_email''='$emails'string' );
        }

        return 
$pieces implode$relation "$pieces ) : '';
    }

    
/**
     * Processes fields related to the operational data table.
     *
     * @return void
     */
    
private function process_operational_data_table_query_args(): void {
        
$fields array_filter(
            array(
                
'created_via',
                
'woocommerce_version',
                
'prices_include_tax',
                
'order_key',
                
'discount_total_amount',
                
'discount_tax_amount',
                
'shipping_total_amount',
                
'shipping_tax_amount',
            ),
            array( 
$this'arg_isset' )
        );

        if ( ! 
$fields ) {
            return;
        }

        
$this->join(
            
$this->tables['operational_data'],
            
'',
            
'',
            
'inner',
            
true
        
);

        foreach ( 
$fields as $arg_key ) {
            
$this->where[] = $this->where$this->tables['operational_data'], $arg_key'='$this->args$arg_key ], $this->mappings['operational_data'][ $arg_key ]['type'] );
        }
    }

    
/**
     * Processes fields related to the addresses table.
     *
     * @return void
     */
    
private function process_addresses_table_query_args(): void {
        global 
$wpdb;

        foreach ( array( 
'billing''shipping' ) as $address_type ) {
            
$fields array_filter(
                array(
                    
$address_type '_first_name',
                    
$address_type '_last_name',
                    
$address_type '_company',
                    
$address_type '_address_1',
                    
$address_type '_address_2',
                    
$address_type '_city',
                    
$address_type '_state',
                    
$address_type '_postcode',
                    
$address_type '_country',
                    
$address_type '_phone',
                ),
                array( 
$this'arg_isset' )
            );

            if ( ! 
$fields ) {
                continue;
            }

            
$this->join(
                
$this->tables['addresses'],
                
$address_type,
                
$wpdb->prepare"{$this->tables['orders']}.id = {$address_type}.order_id AND {$address_type}.address_type = %s"$address_type ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                
'inner',
                
false
            
);

            foreach ( 
$fields as $arg_key ) {
                
$column_name str_replace"{$address_type}_"''$arg_key );

                
$this->where[] = $this->where(
                    
$address_type,
                    
$column_name,
                    
'=',
                    
$this->args$arg_key ],
                    
$this->mappings"{$address_type}_address" ][ $column_name ]['type']
                );
            }
        }
    }

    
/**
     * Generates the ORDER BY clause.
     *
     * @return void
     */
    
private function process_orderby(): void {
        
// 'order' and 'orderby' vars.
        
$this->args['order'] = $this->sanitize_order$this->args['order'] ?? '' );
        
$this->sanitize_order_orderby();

        
$orderby $this->args['orderby'];

        if ( 
'none' === $orderby ) {
            
$this->orderby '';
            return;
        }

        if ( 
'include' === $orderby || 'post__in' === $orderby ) {
            
$ids $this->args['id'] ?? $this->args['includes'];
            if ( empty( 
$ids ) ) {
                return;
            }
            
$ids           array_map'absint'$ids );
            
$this->orderby = array( "FIELD( {$this->tables['orders']}.id, " implode','$ids ) . ' )' );
            return;
        }

        
$meta_orderby_keys $this->meta_query $this->meta_query->get_orderby_keys() : array();

        
$orderby_array = array();
        foreach ( 
$this->args['orderby'] as $_orderby => $order ) {
            if ( 
in_array$_orderby$meta_orderby_keystrue ) ) {
                
$_orderby $this->meta_query->get_orderby_clause_for_key$_orderby );
            }

            
$orderby_array[] = "{$_orderby} {$order}";
        }

        
$this->orderby $orderby_array;
    }

    
/**
     * Generates the limits to be used in the LIMIT clause.
     *
     * @return void
     */
    
private function process_limit(): void {
        
$row_count = ( $this->arg_isset'limit' ) ? (int) $this->args['limit'] : false );
        
$page      = ( $this->arg_isset'page' ) ? absint$this->args['page'] ) : );
        
$offset    = ( $this->arg_isset'offset' ) ? absint$this->args['offset'] ) : false );

        
// Bool false indicates no limit was specified; less than -1 means an invalid value was passed (such as -3).
        
if ( false === $row_count || $row_count < -) {
            return;
        }

        if ( 
false === $offset && $row_count > -) {
            
$offset = (int) ( ( $page ) * $row_count );
        }

        
$this->limits = array( $offset$row_count );
    }

    
/**
     * Checks if a query var is set (i.e. not one of the "skipped values").
     *
     * @param string $arg_key Query var.
     * @return bool TRUE if query var is set.
     */
    
public function arg_issetstring $arg_key ): bool {
        return ( isset( 
$this->args$arg_key ] ) && ! in_array$this->args$arg_key ], self::SKIPPED_VALUEStrue ) );
    }

    
/**
     * Runs the SQL query.
     *
     * @return void
     */
    
private function run_query(): void {
        global 
$wpdb;

        
// Run query.
        
$this->orders array_map'absint'$wpdb->get_col$this->sql ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        // Set max_num_pages and found_orders if necessary.
        
if ( ( $this->arg_isset'no_found_rows' ) && $this->args['no_found_rows'] ) || empty( $this->orders ) ) {
            return;
        }

        if ( 
$this->limits ) {
            
$this->found_orders  absint$wpdb->get_var$this->count_sql ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            
$this->max_num_pages = (int) ceil$this->found_orders $this->args['limit'] );
        } else {
            
$this->found_orders count$this->orders );
        }
    }

    
/**
     * Make some private available for backwards compatibility.
     *
     * @param string $name Property to get.
     * @return mixed
     */
    
public function __getstring $name ) {
        switch ( 
$name ) {
            case 
'found_orders':
            case 
'found_posts':
                return 
$this->found_orders;
            case 
'max_num_pages':
                return 
$this->max_num_pages;
            case 
'posts':
            case 
'orders':
                return 
$this->orders;
            case 
'request':
                return 
$this->sql;
            default:
                break;
        }
    }

    
/**
     * Returns the value of one of the query arguments.
     *
     * @param string $arg_name Query var.
     * @return mixed
     */
    
public function getstring $arg_name ) {
        return 
$this->args$arg_name ] ?? null;
    }

    
/**
     * Returns the name of one of the OrdersTableDatastore tables.
     *
     * @param string $table_id Table identifier. One of 'orders', 'operational_data', 'addresses', 'meta'.
     * @return string The prefixed table name.
     * @throws \Exception When table ID is not found.
     */
    
public function get_table_namestring $table_id '' ): string {
        if ( ! isset( 
$this->tables$table_id ] ) ) {
            
// Translators: %s is a table identifier.
            
throw new \Exceptionsprintf__'Invalid table id: %s.''woocommerce' ), $table_id ) );
        }

        return 
$this->tables$table_id ];
    }

    
/**
     * Finds table and mapping information about a field or column.
     *
     * @param string $field Field to look for in `<mapping|field_name>.<column|field_name>` format or just `<field_name>`.
     * @return false|array {
     *     @type string $table      Full table name where the field is located.
     *     @type string $mapping_id Unprefixed table or mapping name.
     *     @type string $field_name Name of the corresponding order field.
     *     @type string $column     Column in $table that corresponds to the field.
     *     @type string $type       Field type.
     * }
     */
    
public function get_field_mapping_info$field ) {
        global 
$wpdb;

        
$result = array(
            
'table'       => '',
            
'mapping_id'  => '',
            
'field_name'  => '',
            
'column'      => '',
            
'column_type' => '',
        );

        
$mappings_to_search = array();

        if ( 
false !== strstr$field'.' ) ) {
            list( 
$mapping_or_table$field_name_or_col ) = explode'.'$field );

            
$mapping_or_table substr$mapping_or_table0strlen$wpdb->prefix ) ) === $wpdb->prefix substr$mapping_or_tablestrlen$wpdb->prefix ) ) : $mapping_or_table;
            
$mapping_or_table 'wc_' === substr$mapping_or_table0) ? substr$mapping_or_table) : $mapping_or_table;

            if ( isset( 
$this->mappings$mapping_or_table ] ) ) {
                if ( isset( 
$this->mappings$mapping_or_table ][ $field_name_or_col ] ) ) {
                    
$result['mapping_id'] = $mapping_or_table;
                    
$result['column']     = $field_name_or_col;
                } else {
                    
$mappings_to_search = array( $mapping_or_table );
                }
            }
        } else {
            
$field_name_or_col  $field;
            
$mappings_to_search array_keys$this->mappings );
        }

        foreach ( 
$mappings_to_search as $mapping_id ) {
            foreach ( 
$this->mappings$mapping_id ] as $column_name => $column_data ) {
                if ( isset( 
$column_data['name'] ) && $column_data['name'] === $field_name_or_col ) {
                    
$result['mapping_id'] = $mapping_id;
                    
$result['column']     = $column_name;
                    break 
2;
                }
            }
        }

        if ( ! 
$result['mapping_id'] || ! $result['column'] ) {
            return 
false;
        }

        
$field_info $this->mappings$result['mapping_id'] ][ $result['column'] ];

        
$result['field_name']  = $field_info['name'];
        
$result['column_type'] = $field_info['type'];
        
$result['table']       = ( in_array$result['mapping_id'], array( 'billing_address''shipping_address' ), true ) )
                                ? 
$this->tables['addresses']
                                : 
$this->tables$result['mapping_id'] ];

        return 
$result;
    }
}