/var/www/html_us/wp-content/plugins/woocommerce/src/Internal/OrderCouponDataMigrator.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
<?php

namespace Automattic\WooCommerce\Internal;

use 
Automattic\WooCommerce\Internal\BatchProcessing\BatchProcessingController;
use 
Automattic\WooCommerce\Internal\BatchProcessing\BatchProcessorInterface;
use 
Automattic\WooCommerce\Utilities\StringUtil;
use 
\Exception;

/**
 * This class is intended to be used with BatchProcessingController and converts verbose
 * 'coupon_data' metadata entries in coupon line items (corresponding to coupons applied to orders)
 * into simplified 'coupon_info' entries. See WC_Coupon::get_short_info.
 *
 * Additionally, this class manages the "Convert order coupon data" tool.
 */
class OrderCouponDataMigrator implements BatchProcessorInterfaceRegisterHooksInterface {

    
/**
     * Register hooks for the class.
     */
    
public function register() {
        
add_filter'woocommerce_debug_tools', array( $this'handle_woocommerce_debug_tools' ), 999);
    }

    
/**
     * Get a user-friendly name for this processor.
     *
     * @return string Name of the processor.
     */
    
public function get_name(): string {
        return 
"Coupon line item 'coupon_data' to 'coupon_info' metadata migrator";
    }

    
/**
     * Get a user-friendly description for this processor.
     *
     * @return string Description of what this processor does.
     */
    
public function get_description(): string {
        return 
"Migrates verbose metadata about coupons applied to an order ('coupon_data' metadata key in coupon line items) to simplified metadata ('coupon_info' keys)";
    }

    
/**
     * Get the total number of pending items that require processing.
     *
     * @return int Number of items pending processing.
     */
    
public function get_total_pending_count(): int {
        global 
$wpdb;

        return 
$wpdb->get_var(
            
$wpdb->prepare(
                
"SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key=%s",
                
'coupon_data'
            
)
        );
    }

    
/**
     * Returns the next batch of items that need to be processed.
     * A batch in this context is a list of 'meta_id' values from the wp_woocommerce_order_itemmeta table.
     *
     * @param int $size Maximum size of the batch to be returned.
     *
     * @return array Batch of items to process, containing $size or less items.
     */
    
public function get_next_batch_to_processint $size ): array {
        global 
$wpdb;

        
$meta_ids $wpdb->get_col(
            
$wpdb->prepare(
                
"SELECT meta_id FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key=%s ORDER BY meta_id ASC LIMIT %d",
                
'coupon_data',
                
$size
            
)
        );

        return 
array_map'absint'$meta_ids );
    }

    
/**
     * Process data for the supplied batch. See the convert_item method.
     *
     * @throw \Exception Something went wrong while processing the batch.
     *
     * @param array $batch Batch to process, as returned by 'get_next_batch_to_process'.
     */
    
public function process_batch( array $batch ): void {
        global 
$wpdb;

        if ( empty( 
$batch ) ) {
            return;
        }

        
$meta_ids StringUtil::to_sql_list$batch );

        
$meta_ids_and_values $wpdb->get_results(
            
//phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            
"SELECT meta_id,meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_id IN $meta_ids",
            
ARRAY_N
        
);

        foreach ( 
$meta_ids_and_values as $meta_id_and_value ) {
            try {
                
$this->convert_item( (int) $meta_id_and_value[0], $meta_id_and_value[1] );
            } catch ( 
Exception $ex ) {
                
wc_get_logger()->errorStringUtil::class_name_without_namespaceself::class ) . ": when converting meta row with id {$meta_id_and_value[0]}{$ex->getMessage()});
            }
        }
    }

    
/**
     * Convert one verbose 'coupon_data' entry into a simplified 'coupon_info' entry.
     *
     * The existing database row is updated in place, both the 'meta_key' and the 'meta_value' columns.
     *
     * @param int    $meta_id Value of 'meta_id' of the row being converted.
     * @param string $meta_value Value of 'meta_value' of the row being converted.
     * @throws Exception Database error.
     */
    
private function convert_itemint $meta_idstring $meta_value ) {
        global 
$wpdb;

        
//phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize
        
$coupon_data unserialize$meta_value );

        
$temp_coupon = new \WC_Coupon();
        
$temp_coupon->set_props$coupon_data );

        
//phpcs:disable WordPress.DB.SlowDBQuery
        
$wpdb->update(
            
"{$wpdb->prefix}woocommerce_order_itemmeta",
            array(
                
'meta_key'   => 'coupon_info',
                
'meta_value' => $temp_coupon->get_short_info(),
            ),
            array( 
'meta_id' => $meta_id )
        );
        
//phpcs:enable WordPress.DB.SlowDBQuery

        
if ( $wpdb->last_error ) {
            throw new 
Exception$wpdb->last_error );
        }
    }

    
/**
     * Default (preferred) batch size to pass to 'get_next_batch_to_process'.
     *
     * @return int Default batch size.
     */
    
public function get_default_batch_size(): int {
        return 
1000;
    }

    
/**
     * Add the tool to start or stop the background process that converts order coupon metadata entries.
     *
     * @param array $tools Old tools array.
     * @return array Updated tools array.
     *
     * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed.
     */
    
public function handle_woocommerce_debug_tools( array $tools ): array {
        
$batch_processor wc_get_container()->getBatchProcessingController::class );
        
$pending_count   $this->get_total_pending_count();

        if ( 
=== $pending_count ) {
            
$tools['start_convert_order_coupon_data'] = array(
                
'name'     => __'Start converting order coupon data to the simplified format''woocommerce' ),
                
'button'   => __'Start converting''woocommerce' ),
                
'disabled' => true,
                
'desc'     => __'This will convert <code>coupon_data</code> order item meta entries to simplified <code>coupon_info</code> entries. The conversion will happen overtime in the background (via Action Scheduler). There are currently no entries to convert.''woocommerce' ),
            );
        } elseif ( 
$batch_processor->is_enqueuedself::class ) ) {
            
$tools['stop_convert_order_coupon_data'] = array(
                
'name'     => __'Stop converting order coupon data to the simplified format''woocommerce' ),
                
'button'   => __'Stop converting''woocommerce' ),
                
'desc'     =>
                    
/* translators: %d=count of entries pending conversion */
                    
sprintf__'This will stop the background process that converts <code>coupon_data</code> order item meta entries to simplified <code>coupon_info</code> entries. There are currently %d entries that can be converted.''woocommerce' ), $pending_count ),
                
'callback' => array( $this'dequeue' ),
            );
        } else {
            
$tools['start_converting_order_coupon_data'] = array(
                
'name'     => __'Convert order coupon data to the simplified format''woocommerce' ),
                
'button'   => __'Start converting''woocommerce' ),
                
'desc'     =>
                    
/* translators: %d=count of entries pending conversion */
                    
sprintf__'This will convert <code>coupon_data</code> order item meta entries to simplified <code>coupon_info</code> entries. The conversion will happen overtime in the background (via Action Scheduler). There are currently %d entries that can be converted.''woocommerce' ), $pending_count ),
                
'callback' => array( $this'enqueue' ),
            );
        }

        return 
$tools;
    }

    
/**
     * Start the background process for coupon data conversion.
     *
     * @return string Informative string to show after the tool is triggered in UI.
     *
     * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed.
     */
    
public function enqueue(): string {
        
$batch_processor wc_get_container()->getBatchProcessingController::class );
        if ( 
$batch_processor->is_enqueuedself::class ) ) {
            return 
__'Background process for coupon meta conversion already started, nothing done.''woocommerce' );
        }

        
$batch_processor->enqueue_processorself::class );
        return 
__'Background process for coupon meta conversion started''woocommerce' );
    }

    
/**
     * Stop the background process for coupon data conversion.
     *
     * @return string Informative string to show after the tool is triggered in UI.
     *
     * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed.
     */
    
public function dequeue(): string {
        
$batch_processor wc_get_container()->getBatchProcessingController::class );
        if ( ! 
$batch_processor->is_enqueuedself::class ) ) {
            return 
__'Background process for coupon meta conversion not started, nothing done.''woocommerce' );
        }

        
$batch_processor->remove_processorself::class );
        return 
__'Background process for coupon meta conversion stopped''woocommerce' );
    }
}