container = $container; } /** * Indexes a single product into the custom search table. * * @param int $product_id * @return bool */ public function index_product($product_id) { $mapper = $this->container->get(DataMapper::class); $data = $mapper->map_product_data($product_id); if (!$data) { // If mapping returns false (e.g. not published), we should remove it from index. $this->remove_product($product_id); return false; } global $wpdb; $table_name = $wpdb->prefix . 'awas_search_index'; // Check if exists $exists = $wpdb->get_var($wpdb->prepare( "SELECT id FROM $table_name WHERE object_id = %d AND variation_id = %d", $data['object_id'], $data['variation_id'] )); if ($exists) { // Update $wpdb->update( $table_name, $data, ['id' => $exists], ['%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s'], ['%d'] ); } else { // Insert $wpdb->insert( $table_name, $data, ['%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s'] ); } return true; } /** * Removes a product from the index. * * @param int $product_id */ public function remove_product($product_id) { global $wpdb; $table_name = $wpdb->prefix . 'awas_search_index'; $wpdb->delete( $table_name, ['object_id' => $product_id], ['%d'] ); // Also remove its variations $wpdb->delete( $table_name, ['variation_id' => $product_id], ['%d'] ); } public function truncate_index() { global $wpdb; $table_name = $wpdb->prefix . 'awas_search_index'; $wpdb->query("TRUNCATE TABLE $table_name"); } }