Automattic\WooCommerce\Internal\DataStores\Orders

OrdersTableFieldQuery::generate_where_for_clause()privateWC 1.0

Generates an SQL WHERE clause for a given field_query atomic clause.

Method of the class: OrdersTableFieldQuery{}

No Hooks.

Return

String. An SQL WHERE clause or an empty string if $clause is invalid.

Usage

// private - for code of main (parent) class only
$result = $this->generate_where_for_clause( $clause ): string;
$clause(array) (required)
An atomic field_query clause.

OrdersTableFieldQuery::generate_where_for_clause() code WC 7.1.1

private function generate_where_for_clause( $clause ): string {
	global $wpdb;

	$clause_value = $clause['value'] ?? '';

	if ( in_array( $clause['compare'], array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
		if ( ! is_array( $clause_value ) ) {
			$clause_value = preg_split( '/[,\s]+/', $clause_value );
		}
	} elseif ( is_string( $clause_value ) ) {
		$clause_value = trim( $clause_value );
	}

	$clause_compare = $clause['compare'];

	switch ( $clause_compare ) {
		case 'IN':
		case 'NOT IN':
			$where = $wpdb->prepare( '(' . substr( str_repeat( ',%s', count( $clause_value ) ), 1 ) . ')', $clause_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			break;
		case 'BETWEEN':
		case 'NOT BETWEEN':
			$where = $wpdb->prepare( '%s AND %s', $clause_value[0], $clause_value[1] ?? $clause_value[0] );
			break;
		case 'LIKE':
		case 'NOT LIKE':
			$where = $wpdb->prepare( '%s', '%' . $wpdb->esc_like( $clause_value ) . '%' );
			break;
		case 'EXISTS':
			// EXISTS with a value is interpreted as '='.
			if ( $clause_value ) {
				$clause_compare = '=';
				$where          = $wpdb->prepare( '%s', $clause_value );
			} else {
				$clause_compare = 'IS NOT';
				$where          = 'NULL';
			}

			break;
		case 'NOT EXISTS':
			// 'value' is ignored for NOT EXISTS.
			$clause_compare = 'IS';
			$where          = 'NULL';
			break;
		default:
			$where = $wpdb->prepare( '%s', $clause_value );
			break;
	}

	if ( $where ) {
		if ( 'CHAR' === $clause['cast'] ) {
			return "`{$clause['alias']}`.`{$clause['column']}` {$clause_compare} {$where}";
		} else {
			return "CAST(`{$clause['alias']}`.`{$clause['column']}` AS {$clause['cast']}) {$clause_compare} {$where}";
		}
	}

	return '';
}