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rc.2 3.1.0 6.2.1 3.1.1 6.2.2 3.1.2 6.2.3 3.2.0 6.3.0 3.2.1 6.3.0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / src / Internal / DataStores / Orders / OrdersTableMetaQuery.php
woocommerce / src / Internal / DataStores / Orders Last commit date
CustomOrdersTableController.php 3 months ago DataSynchronizer.php 7 months ago LegacyDataCleanup.php 1 year ago LegacyDataHandler.php 5 months ago OrdersTableDataStore.php 1 month ago OrdersTableDataStoreMeta.php 1 year ago OrdersTableFieldQuery.php 2 years ago OrdersTableMetaQuery.php 1 year ago OrdersTableQuery.php 1 month ago OrdersTableRefundDataStore.php 1 month ago OrdersTableSearchQuery.php 11 months ago
OrdersTableMetaQuery.php
663 lines
1 <?php
2 namespace Automattic\WooCommerce\Internal\DataStores\Orders;
3
4 defined( 'ABSPATH' ) || exit;
5
6 /**
7 * Class used to implement meta queries for the orders table datastore via {@see OrdersTableQuery}.
8 * Heavily inspired by WordPress' own `WP_Meta_Query` for backwards compatibility reasons.
9 *
10 * Parts of the implementation have been adapted from {@link https://core.trac.wordpress.org/browser/tags/6.0.1/src/wp-includes/class-wp-meta-query.php}.
11 */
12 class OrdersTableMetaQuery {
13
14 /**
15 * List of non-numeric SQL operators used for comparisons in meta queries.
16 *
17 * @var array
18 */
19 private const NON_NUMERIC_OPERATORS = array(
20 '=',
21 '!=',
22 'LIKE',
23 'NOT LIKE',
24 'IN',
25 'NOT IN',
26 'EXISTS',
27 'NOT EXISTS',
28 'RLIKE',
29 'REGEXP',
30 'NOT REGEXP',
31 );
32
33 /**
34 * List of numeric SQL operators used for comparisons in meta queries.
35 *
36 * @var array
37 */
38 private const NUMERIC_OPERATORS = array(
39 '>',
40 '>=',
41 '<',
42 '<=',
43 'BETWEEN',
44 'NOT BETWEEN',
45
46 );
47
48 /**
49 * Prefix used when generating aliases for the metadata table.
50 *
51 * @var string
52 */
53 private const ALIAS_PREFIX = 'meta';
54
55 /**
56 * Name of the main orders table.
57 *
58 * @var string
59 */
60 private $meta_table = '';
61
62 /**
63 * Name of the metadata table.
64 *
65 * @var string
66 */
67 private $orders_table = '';
68
69 /**
70 * Sanitized `meta_query`.
71 *
72 * @var array
73 */
74 private $queries = array();
75
76 /**
77 * Flat list of clauses by name.
78 *
79 * @var array
80 */
81 private $flattened_clauses = array();
82
83 /**
84 * JOIN clauses to add to the main SQL query.
85 *
86 * @var array
87 */
88 private $join = array();
89
90 /**
91 * WHERE clauses to add to the main SQL query.
92 *
93 * @var array
94 */
95 private $where = array();
96
97 /**
98 * Table aliases in use by the meta query. Used to optimize JOINs when possible.
99 *
100 * @var array
101 */
102 private $table_aliases = array();
103
104 /**
105 * Constructor.
106 *
107 * @param OrdersTableQuery $q The main query being performed.
108 */
109 public function __construct( OrdersTableQuery $q ) {
110 $meta_query = $q->get( 'meta_query' );
111
112 if ( ! $meta_query ) {
113 return;
114 }
115
116 $this->queries = $this->sanitize_meta_query( $meta_query );
117
118 $this->meta_table = $q->get_table_name( 'meta' );
119 $this->orders_table = $q->get_table_name( 'orders' );
120
121 $this->build_query();
122 }
123
124 /**
125 * Returns JOIN and WHERE clauses to be appended to the main SQL query.
126 *
127 * @return array {
128 * @type string $join JOIN clause.
129 * @type string $where WHERE clause.
130 * }
131 */
132 public function get_sql_clauses(): array {
133 return array(
134 'join' => $this->sanitize_join( $this->join ),
135 'where' => $this->flatten_where_clauses( $this->where ),
136 );
137 }
138
139 /**
140 * Returns a list of names (corresponding to meta_query clauses) that can be used as an 'orderby' arg.
141 *
142 * @since 7.4
143 *
144 * @return array
145 */
146 public function get_orderby_keys(): array {
147 if ( ! $this->flattened_clauses ) {
148 return array();
149 }
150
151 $keys = array();
152 $keys[] = 'meta_value';
153 $keys[] = 'meta_value_num';
154
155 $first_clause = reset( $this->flattened_clauses );
156 if ( $first_clause && ! empty( $first_clause['key'] ) ) {
157 $keys[] = $first_clause['key'];
158 }
159
160 $keys = array_merge(
161 $keys,
162 array_keys( $this->flattened_clauses )
163 );
164
165 return $keys;
166 }
167
168 /**
169 * Returns an SQL fragment for the given meta_query key that can be used in an ORDER BY clause.
170 * Call {@see 'get_orderby_keys'} to obtain a list of valid keys.
171 *
172 * @since 7.4
173 *
174 * @param string $key The key name.
175 * @return string
176 *
177 * @throws \Exception When an invalid key is passed.
178 */
179 public function get_orderby_clause_for_key( string $key ): string {
180 $clause = false;
181
182 if ( isset( $this->flattened_clauses[ $key ] ) ) {
183 $clause = $this->flattened_clauses[ $key ];
184 } else {
185 $first_clause = reset( $this->flattened_clauses );
186
187 if ( $first_clause && ! empty( $first_clause['key'] ) ) {
188 if ( 'meta_value_num' === $key ) {
189 return "{$first_clause['alias']}.meta_value+0";
190 }
191
192 if ( 'meta_value' === $key || $first_clause['key'] === $key ) {
193 $clause = $first_clause;
194 }
195 }
196 }
197
198 if ( ! $clause ) {
199 // translators: %s is a meta_query key.
200 throw new \Exception( sprintf( __( 'Invalid meta_query clause key: %s.', 'woocommerce' ), $key ) );
201 }
202
203 return "CAST({$clause['alias']}.meta_value AS {$clause['cast']})";
204 }
205
206 /**
207 * Checks whether a given meta_query clause is atomic or not (i.e. not nested).
208 *
209 * @param array $arg The meta_query clause.
210 * @return boolean TRUE if atomic, FALSE otherwise.
211 */
212 private function is_atomic( array $arg ): bool {
213 return isset( $arg['key'] ) || isset( $arg['value'] );
214 }
215
216 /**
217 * Sanitizes the meta_query argument.
218 *
219 * @param array $q A meta_query array.
220 * @return array A sanitized meta query array.
221 */
222 private function sanitize_meta_query( array $q ): array {
223 $sanitized = array();
224
225 foreach ( $q as $key => $arg ) {
226 if ( 'relation' === $key ) {
227 $relation = $arg;
228 } elseif ( ! is_array( $arg ) ) {
229 continue;
230 } elseif ( $this->is_atomic( $arg ) ) {
231 if ( isset( $arg['value'] ) && array() === $arg['value'] ) {
232 unset( $arg['value'] );
233 }
234
235 $arg['compare'] = isset( $arg['compare'] ) ? strtoupper( $arg['compare'] ) : ( isset( $arg['value'] ) && is_array( $arg['value'] ) ? 'IN' : '=' );
236 $arg['compare_key'] = isset( $arg['compare_key'] ) ? strtoupper( $arg['compare_key'] ) : ( isset( $arg['key'] ) && is_array( $arg['key'] ) ? 'IN' : '=' );
237
238 if ( ! in_array( $arg['compare'], self::NON_NUMERIC_OPERATORS, true ) && ! in_array( $arg['compare'], self::NUMERIC_OPERATORS, true ) ) {
239 $arg['compare'] = '=';
240 }
241
242 if ( ! in_array( $arg['compare_key'], self::NON_NUMERIC_OPERATORS, true ) ) {
243 $arg['compare_key'] = '=';
244 }
245
246 $sanitized[ $key ] = $arg;
247 $sanitized[ $key ]['index'] = $key;
248 } else {
249 $sanitized_arg = $this->sanitize_meta_query( $arg );
250
251 if ( $sanitized_arg ) {
252 $sanitized[ $key ] = $sanitized_arg;
253 }
254 }
255 }
256
257 if ( $sanitized ) {
258 $sanitized['relation'] = 1 === count( $sanitized ) ? 'OR' : $this->sanitize_relation( $relation ?? 'AND' );
259 }
260
261 return $sanitized;
262 }
263
264 /**
265 * Makes sure we use an AND or OR relation. Defaults to AND.
266 *
267 * @param string $relation An unsanitized relation prop.
268 * @return string
269 */
270 private function sanitize_relation( string $relation ): string {
271 if ( ! empty( $relation ) && 'OR' === strtoupper( $relation ) ) {
272 return 'OR';
273 }
274
275 return 'AND';
276 }
277
278 /**
279 * Returns the correct type for a given meta type.
280 *
281 * @param string $type MySQL type.
282 * @return string MySQL type.
283 */
284 private function sanitize_cast_type( string $type = '' ): string {
285 $meta_type = strtoupper( $type );
286
287 if ( ! $meta_type || ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) ) {
288 return 'CHAR';
289 }
290
291 if ( 'NUMERIC' === $meta_type ) {
292 $meta_type = 'SIGNED';
293 }
294
295 return $meta_type;
296 }
297
298 /**
299 * Makes sure a JOIN array does not have duplicates.
300 *
301 * @param array $join A JOIN array.
302 * @return array A sanitized JOIN array.
303 */
304 private function sanitize_join( array $join ): array {
305 return array_filter( array_unique( array_map( 'trim', $join ) ) );
306 }
307
308 /**
309 * Flattens a nested WHERE array.
310 *
311 * @param array $where A possibly nested WHERE array with AND/OR operators.
312 * @return string An SQL WHERE clause.
313 */
314 private function flatten_where_clauses( $where ): string {
315 if ( is_string( $where ) ) {
316 return trim( $where );
317 }
318
319 $chunks = array();
320 $operator = $this->sanitize_relation( $where['operator'] ?? '' );
321
322 foreach ( $where as $key => $w ) {
323 if ( 'operator' === $key ) {
324 continue;
325 }
326
327 $flattened = $this->flatten_where_clauses( $w );
328 if ( $flattened ) {
329 $chunks[] = $flattened;
330 }
331 }
332
333 if ( $chunks ) {
334 return '(' . implode( " {$operator} ", $chunks ) . ')';
335 } else {
336 return '';
337 }
338 }
339
340 /**
341 * Builds all the required internal bits for this meta query.
342 *
343 * @return void
344 */
345 private function build_query(): void {
346 if ( ! $this->queries ) {
347 return;
348 }
349
350 $queries = $this->queries;
351 $sql_where = $this->process( $queries );
352 $this->where = $sql_where;
353 }
354
355 /**
356 * Processes meta_query entries and generates the necessary table aliases, JOIN statements and WHERE conditions.
357 *
358 * @param array $arg A meta query.
359 * @param null|array $parent The parent of the element being processed.
360 * @return array A nested array of WHERE conditions.
361 */
362 private function process( array &$arg, &$parent = null ): array {
363 $where = array();
364
365 if ( $this->is_atomic( $arg ) ) {
366 $arg['alias'] = $this->find_or_create_table_alias_for_clause( $arg, $parent );
367 $arg['cast'] = $this->sanitize_cast_type( $arg['type'] ?? '' );
368
369 $where = array_filter(
370 array(
371 $this->generate_where_for_clause_key( $arg ),
372 $this->generate_where_for_clause_value( $arg ),
373 )
374 );
375
376 // Store clauses by their key for ORDER BY purposes.
377 $flat_clause_key = is_int( $arg['index'] ) ? $arg['alias'] : $arg['index'];
378
379 $unique_flat_key = $flat_clause_key;
380 $i = 1;
381 while ( isset( $this->flattened_clauses[ $unique_flat_key ] ) ) {
382 $unique_flat_key = $flat_clause_key . '-' . $i;
383 ++$i;
384 }
385
386 $this->flattened_clauses[ $unique_flat_key ] =& $arg;
387 } else {
388 // Nested.
389 $relation = $arg['relation'];
390 unset( $arg['relation'] );
391 $chunks = array();
392 foreach ( $arg as $index => &$clause ) {
393 $chunks[] = $this->process( $clause, $arg );
394 }
395
396 // Merge chunks of the form OR(m) with the surrounding clause.
397 if ( 1 === count( $chunks ) ) {
398 $where = $chunks[0];
399 } else {
400 $where = array_merge(
401 array(
402 'operator' => $relation,
403 ),
404 $chunks
405 );
406 }
407 }
408
409 return $where;
410 }
411
412 /**
413 * Generates a JOIN clause to handle an atomic meta_query clause.
414 *
415 * @param array $clause An atomic meta_query clause.
416 * @param string $alias Metadata table alias to use.
417 * @return string An SQL JOIN clause.
418 */
419 private function generate_join_for_clause( array $clause, string $alias ): string {
420 global $wpdb;
421
422 if ( 'NOT EXISTS' === $clause['compare'] ) {
423 if ( 'LIKE' === $clause['compare_key'] ) {
424 return $wpdb->prepare(
425 "LEFT JOIN {$this->meta_table} AS {$alias} ON ( {$this->orders_table}.id = {$alias}.order_id AND {$alias}.meta_key LIKE %s )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
426 '%' . $wpdb->esc_like( $clause['key'] ) . '%'
427 );
428 } else {
429 return $wpdb->prepare(
430 "LEFT JOIN {$this->meta_table} AS {$alias} ON ( {$this->orders_table}.id = {$alias}.order_id AND {$alias}.meta_key = %s )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
431 $clause['key']
432 );
433 }
434 }
435
436 return "INNER JOIN {$this->meta_table} AS {$alias} ON ( {$this->orders_table}.id = {$alias}.order_id )";
437 }
438
439 /**
440 * Finds a common table alias that the meta_query clause can use, or creates one.
441 *
442 * @param array $clause An atomic meta_query clause.
443 * @param array $parent_query The parent query this clause is in.
444 * @return string A table alias for use in an SQL JOIN clause.
445 */
446 private function find_or_create_table_alias_for_clause( array $clause, array $parent_query ): string {
447 if ( ! empty( $clause['alias'] ) ) {
448 return $clause['alias'];
449 }
450
451 $alias = false;
452 $siblings = array_filter(
453 $parent_query,
454 array( __CLASS__, 'is_atomic' )
455 );
456
457 foreach ( $siblings as $sibling ) {
458 if ( empty( $sibling['alias'] ) ) {
459 continue;
460 }
461
462 if ( $this->is_operator_compatible_with_shared_join( $clause, $sibling, $parent_query['relation'] ?? 'AND' ) ) {
463 $alias = $sibling['alias'];
464 break;
465 }
466 }
467
468 if ( ! $alias ) {
469 $alias = self::ALIAS_PREFIX . count( $this->table_aliases );
470 $this->join[] = $this->generate_join_for_clause( $clause, $alias );
471 $this->table_aliases[] = $alias;
472 }
473
474 return $alias;
475 }
476
477 /**
478 * Checks whether two meta_query clauses can share a JOIN.
479 *
480 * @param array $clause An atomic meta_query clause.
481 * @param array $sibling An atomic meta_query clause.
482 * @param string $relation The relation involving both clauses.
483 * @return boolean TRUE if the clauses can share a table alias, FALSE otherwise.
484 */
485 private function is_operator_compatible_with_shared_join( array $clause, array $sibling, string $relation = 'AND' ): bool {
486 if ( ! $this->is_atomic( $clause ) || ! $this->is_atomic( $sibling ) ) {
487 return false;
488 }
489
490 $valid_operators = array();
491
492 if ( 'OR' === $relation ) {
493 $valid_operators = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
494 } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
495 $valid_operators = array( '!=', 'NOT IN', 'NOT LIKE' );
496 }
497
498 return in_array( strtoupper( $clause['compare'] ), $valid_operators, true ) && in_array( strtoupper( $sibling['compare'] ), $valid_operators, true );
499 }
500
501 /**
502 * Generates an SQL WHERE clause for a given meta_query atomic clause based on its meta key.
503 * Adapted from WordPress' `WP_Meta_Query::get_sql_for_clause()` method.
504 *
505 * @param array $clause An atomic meta_query clause.
506 * @return string An SQL WHERE clause or an empty string if $clause is invalid.
507 */
508 private function generate_where_for_clause_key( array $clause ): string {
509 global $wpdb;
510
511 if ( ! array_key_exists( 'key', $clause ) ) {
512 return '';
513 }
514
515 if ( 'NOT EXISTS' === $clause['compare'] ) {
516 return "{$clause['alias']}.order_id IS NULL";
517 }
518
519 $alias = $clause['alias'];
520
521 $meta_compare_string_start = '';
522 $meta_compare_string_end = '';
523 $subquery_alias = '';
524 if ( in_array( $clause['compare_key'], array( '!=', 'NOT IN', 'NOT LIKE', 'NOT EXISTS', 'NOT REGEXP' ), true ) ) {
525 $i = count( $this->table_aliases );
526 $subquery_alias = self::ALIAS_PREFIX . $i;
527 $this->table_aliases[] = $subquery_alias;
528
529 $meta_compare_string_start = 'NOT EXISTS (';
530 $meta_compare_string_start .= "SELECT 1 FROM {$this->meta_table} {$subquery_alias} ";
531 $meta_compare_string_start .= "WHERE {$subquery_alias}.order_id = {$alias}.order_id ";
532 $meta_compare_string_end = 'LIMIT 1';
533 $meta_compare_string_end .= ')';
534 }
535
536 switch ( $clause['compare_key'] ) {
537 case '=':
538 case 'EXISTS':
539 $where = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
540 break;
541 case 'LIKE':
542 $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%';
543 $where = $wpdb->prepare( "$alias.meta_key LIKE %s", $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
544 break;
545 case 'IN':
546 $meta_compare_string = "$alias.meta_key IN (" . substr( str_repeat( ',%s', count( (array) $clause['key'] ) ), 1 ) . ')';
547 $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
548 break;
549 case 'RLIKE':
550 case 'REGEXP':
551 $operator = $clause['compare_key'];
552 if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) {
553 $cast = 'BINARY';
554 } else {
555 $cast = '';
556 }
557 $where = $wpdb->prepare( "$alias.meta_key $operator $cast %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
558 break;
559 case '!=':
560 case 'NOT EXISTS':
561 $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key = %s " . $meta_compare_string_end;
562 $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
563 break;
564 case 'NOT LIKE':
565 $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key LIKE %s " . $meta_compare_string_end;
566
567 $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%';
568 $where = $wpdb->prepare( $meta_compare_string, $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
569 break;
570 case 'NOT IN':
571 $array_subclause = '(' . substr( str_repeat( ',%s', count( (array) $clause['key'] ) ), 1 ) . ') ';
572 $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key IN " . $array_subclause . $meta_compare_string_end;
573 $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
574 break;
575 case 'NOT REGEXP':
576 $operator = $clause['compare_key'];
577 if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) {
578 $cast = 'BINARY';
579 } else {
580 $cast = '';
581 }
582
583 $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key REGEXP $cast %s " . $meta_compare_string_end;
584 $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
585 break;
586 default:
587 $where = '';
588 break;
589 }
590
591 return $where;
592 }
593
594 /**
595 * Generates an SQL WHERE clause for a given meta_query atomic clause based on its meta value.
596 * Adapted from WordPress' `WP_Meta_Query::get_sql_for_clause()` method.
597 *
598 * @param array $clause An atomic meta_query clause.
599 * @return string An SQL WHERE clause or an empty string if $clause is invalid.
600 */
601 private function generate_where_for_clause_value( $clause ): string {
602 global $wpdb;
603
604 if ( ! array_key_exists( 'value', $clause ) ) {
605 return '';
606 }
607
608 $meta_value = $clause['value'];
609
610 if ( in_array( $clause['compare'], array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
611 if ( ! is_array( $meta_value ) ) {
612 $meta_value = preg_split( '/[,\s]+/', $meta_value );
613 }
614 } elseif ( is_string( $meta_value ) ) {
615 $meta_value = trim( $meta_value );
616 }
617
618 $meta_compare = $clause['compare'];
619
620 switch ( $meta_compare ) {
621 case 'IN':
622 case 'NOT IN':
623 $where = $wpdb->prepare( '(' . substr( str_repeat( ',%s', count( (array) $meta_value ) ), 1 ) . ')', $meta_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
624 break;
625
626 case 'BETWEEN':
627 case 'NOT BETWEEN':
628 $where = $wpdb->prepare( '%s AND %s', $meta_value[0], $meta_value[1] );
629 break;
630
631 case 'LIKE':
632 case 'NOT LIKE':
633 $where = $wpdb->prepare( '%s', '%' . $wpdb->esc_like( $meta_value ) . '%' );
634 break;
635
636 // EXISTS with a value is interpreted as '='.
637 case 'EXISTS':
638 $meta_compare = '=';
639 $where = $wpdb->prepare( '%s', $meta_value );
640 break;
641
642 // 'value' is ignored for NOT EXISTS.
643 case 'NOT EXISTS':
644 $where = '';
645 break;
646
647 default:
648 $where = $wpdb->prepare( '%s', $meta_value );
649 break;
650 }
651
652 if ( $where ) {
653 if ( 'CHAR' === $clause['cast'] ) {
654 return "{$clause['alias']}.meta_value {$meta_compare} {$where}";
655 } else {
656 return "CAST({$clause['alias']}.meta_value AS {$clause['cast']}) {$meta_compare} {$where}";
657 }
658 }
659
660 return '';
661 }
662 }
663