SearchService.php
60 lines
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types = 1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\Customers; |
| 6 | |
| 7 | use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore; |
| 8 | use Automattic\WooCommerce\Utilities\OrderUtil; |
| 9 | |
| 10 | /** |
| 11 | * Internal API for searching users/customers: no backward compatibility obligation. |
| 12 | */ |
| 13 | final class SearchService { |
| 14 | /** |
| 15 | * Searches users having the billing email (when applicable lookup orders as well) as specified and returns their id. |
| 16 | * |
| 17 | * @param string[] $emails Emails to search for. |
| 18 | * |
| 19 | * @return int[] |
| 20 | */ |
| 21 | public function find_user_ids_by_billing_email_for_coupons_usage_lookup( array $emails ): array { |
| 22 | $emails = array_unique( array_map( 'strtolower', array_map( 'sanitize_email', $emails ) ) ); |
| 23 | |
| 24 | $include_user_ids = array(); |
| 25 | if ( OrderUtil::custom_orders_table_usage_is_enabled() ) { |
| 26 | global $wpdb; |
| 27 | |
| 28 | // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 29 | $placeholders = implode( ', ', array_fill( 0, count( $emails ), '%s' ) ); |
| 30 | $include_user_ids = $wpdb->get_col( |
| 31 | $wpdb->prepare( |
| 32 | "SELECT DISTINCT customer_id FROM %i WHERE billing_email IN ($placeholders)", |
| 33 | OrdersTableDataStore::get_orders_table_name(), |
| 34 | ...$emails |
| 35 | ) |
| 36 | ); |
| 37 | // phpcs:enable |
| 38 | |
| 39 | if ( array() === $include_user_ids ) { |
| 40 | return array(); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | $users_query = new \WP_User_Query( |
| 45 | array( |
| 46 | 'fields' => 'ID', |
| 47 | 'include' => $include_user_ids, |
| 48 | 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query |
| 49 | array( |
| 50 | 'key' => 'billing_email', |
| 51 | 'value' => $emails, |
| 52 | 'compare' => 'IN', |
| 53 | ), |
| 54 | ), |
| 55 | ) |
| 56 | ); |
| 57 | return array_map( 'intval', array_unique( $users_query->get_results() ) ); |
| 58 | } |
| 59 | } |
| 60 |