Completed
Push — update/use-calypso-build-webpa... ( 5e3f8e...d164b3 )
by
unknown
08:39
created

continue_enqueuing()   D

Complexity

Conditions 18
Paths 74

Size

Total Lines 79

Duplication

Lines 6
Ratio 7.59 %

Importance

Changes 0
Metric Value
cc 18
nc 74
nop 2
dl 6
loc 79
rs 4.8666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This class does a full resync of the database by
5
 * enqueuing an outbound action for every single object
6
 * that we care about.
7
 *
8
 * This class, and its related class Jetpack_Sync_Module, contain a few non-obvious optimisations that should be explained:
9
 * - we fire an action called jetpack_full_sync_start so that WPCOM can erase the contents of the cached database
10
 * - for each object type, we page through the object IDs and enqueue them by firing some monitored actions
11
 * - we load the full objects for those IDs in chunks of Jetpack_Sync_Module::ARRAY_CHUNK_SIZE (to reduce the number of MySQL calls)
12
 * - we fire a trigger for the entire array which the Jetpack_Sync_Listener then serializes and queues.
13
 */
14
15
class Jetpack_Sync_Module_Full_Sync extends Jetpack_Sync_Module {
16
	const STATUS_OPTION_PREFIX = 'jetpack_sync_full_';
17
	const FULL_SYNC_TIMEOUT    = 3600;
18
19
	public function name() {
20
		return 'full-sync';
21
	}
22
23
	function init_full_sync_listeners( $callable ) {
24
		// synthetic actions for full sync
25
		add_action( 'jetpack_full_sync_start', $callable );
26
		add_action( 'jetpack_full_sync_end', $callable, 10, 2 );
27
		add_action( 'jetpack_full_sync_cancelled', $callable );
28
	}
29
30
	function init_before_send() {
31
		// this is triggered after actions have been processed on the server
32
		add_action( 'jetpack_sync_processed_actions', array( $this, 'update_sent_progress_action' ) );
33
	}
34
35
	function start( $module_configs = null ) {
36
		$was_already_running = $this->is_started() && ! $this->is_finished();
37
38
		// remove all evidence of previous full sync items and status
39
		$this->reset_data();
40
41
		if ( $was_already_running ) {
42
			/**
43
			 * Fires when a full sync is cancelled.
44
			 *
45
			 * @since 4.2.0
46
			 */
47
			do_action( 'jetpack_full_sync_cancelled' );
48
		}
49
50
		$this->update_status_option( 'started', time() );
51
		$this->update_status_option( 'params', $module_configs );
52
53
		$enqueue_status   = array();
54
		$full_sync_config = array();
55
56
		// default value is full sync
57
		if ( ! is_array( $module_configs ) ) {
58
			$module_configs = array();
59
			foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
60
				$module_configs[ $module->name() ] = true;
61
			}
62
		}
63
64
		// set default configuration, calculate totals, and save configuration if totals > 0
65
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
66
			$module_name   = $module->name();
67
			$module_config = isset( $module_configs[ $module_name ] ) ? $module_configs[ $module_name ] : false;
68
69
			if ( ! $module_config ) {
70
				continue;
71
			}
72
73
			if ( 'users' === $module_name && 'initial' === $module_config ) {
74
				$module_config = $module->get_initial_sync_user_config();
75
			}
76
77
			$enqueue_status[ $module_name ] = false;
78
79
			$total_items = $module->estimate_full_sync_actions( $module_config );
80
81
			// if there's information to process, configure this module
82
			if ( ! is_null( $total_items ) && $total_items > 0 ) {
83
				$full_sync_config[ $module_name ] = $module_config;
84
				$enqueue_status[ $module_name ]   = array(
85
					$total_items,   // total
86
					0,              // queued
87
					false,          // current state
88
				);
89
			}
90
		}
91
92
		$this->set_config( $full_sync_config );
93
		$this->set_enqueue_status( $enqueue_status );
94
95
		/**
96
		 * Fires when a full sync begins. This action is serialized
97
		 * and sent to the server so that it knows a full sync is coming.
98
		 *
99
		 * @since 4.2.0
100
		 */
101
		do_action( 'jetpack_full_sync_start', $full_sync_config );
102
103
		$this->continue_enqueuing( $full_sync_config, $enqueue_status );
104
105
		return true;
106
	}
107
108
	function continue_enqueuing( $configs = null, $enqueue_status = null ) {
109
		if ( ! $this->is_started() || $this->get_status_option( 'queue_finished' ) ) {
110
			return;
111
		}
112
113
		// if full sync queue is full, don't enqueue more items
114
		$max_queue_size_full_sync = Jetpack_Sync_Settings::get_setting( 'max_queue_size_full_sync' );
115
		$full_sync_queue          = new Jetpack_Sync_Queue( 'full_sync' );
116
117
		$available_queue_slots = $max_queue_size_full_sync - $full_sync_queue->size();
118
119
		if ( $available_queue_slots <= 0 ) {
120
			return;
121
		} else {
122
			$remaining_items_to_enqueue = min( Jetpack_Sync_Settings::get_setting( 'max_enqueue_full_sync' ), $available_queue_slots );
123
		}
124
125
		if ( ! $configs ) {
126
			$configs = $this->get_config();
127
		}
128
129
		if ( ! $enqueue_status ) {
130
			$enqueue_status = $this->get_enqueue_status();
131
		}
132
133
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
134
			$module_name = $module->name();
135
136
			// skip module if not configured for this sync or module is done
137
			if ( ! isset( $configs[ $module_name ] )
138
				|| // no module config
139
					! $configs[ $module_name ]
140
				|| // no enqueue status
141
					! $enqueue_status[ $module_name ]
142
				|| // finished enqueuing this module
143
					true === $enqueue_status[ $module_name ][2] ) {
144
				continue;
145
			}
146
147
			list( $items_enqueued, $next_enqueue_state ) = $module->enqueue_full_sync_actions( $configs[ $module_name ], $remaining_items_to_enqueue, $enqueue_status[ $module_name ][2] );
148
149
			$enqueue_status[ $module_name ][2] = $next_enqueue_state;
150
151
			// if items were processed, subtract them from the limit
152
			if ( ! is_null( $items_enqueued ) && $items_enqueued > 0 ) {
153
				$enqueue_status[ $module_name ][1] += $items_enqueued;
154
				$remaining_items_to_enqueue        -= $items_enqueued;
155
			}
156
157
			// stop processing if we've reached our limit of items to enqueue
158
			if ( 0 >= $remaining_items_to_enqueue ) {
159
				$this->set_enqueue_status( $enqueue_status );
160
				return;
161
			}
162
		}
163
164
		$this->set_enqueue_status( $enqueue_status );
165
166
		// setting autoload to true means that it's faster to check whether we should continue enqueuing
167
		$this->update_status_option( 'queue_finished', time(), true );
168
169
		$range = array();
170
		// Only when we are sending the whole range do we want to send also the range
171 View Code Duplication
		if ( isset( $configs['posts'] ) && $configs['posts'] === true ) {
172
			$range['posts'] = $this->get_range( 'posts' );
173
		}
174
175 View Code Duplication
		if ( isset( $configs['comments'] ) && $configs['comments'] === true ) {
176
			$range['comments'] = $this->get_range( 'comments' );
177
		}
178
179
		/**
180
		 * Fires when a full sync ends. This action is serialized
181
		 * and sent to the server.
182
		 *
183
		 * @since 4.2.0
184
		 */
185
		do_action( 'jetpack_full_sync_end', '', $range );
186
	}
187
188
	function get_range( $type ) {
189
		global $wpdb;
190
		if ( ! in_array( $type, array( 'comments', 'posts' ) ) ) {
191
			return array();
192
		}
193
194
		switch ( $type ) {
195
			case 'posts':
196
				$table     = $wpdb->posts;
197
				$id        = 'ID';
198
				$where_sql = Jetpack_Sync_Settings::get_blacklisted_post_types_sql();
199
200
				break;
201
			case 'comments':
202
				$table     = $wpdb->comments;
203
				$id        = 'comment_ID';
204
				$where_sql = Jetpack_Sync_Settings::get_comments_filter_sql();
205
				break;
206
		}
207
		$results = $wpdb->get_results( "SELECT MAX({$id}) as max, MIN({$id}) as min, COUNT({$id}) as count FROM {$table} WHERE {$where_sql}" );
0 ignored issues
show
Bug introduced by
The variable $id does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $table does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $where_sql does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
208
		if ( isset( $results[0] ) ) {
209
			return $results[0];
210
		}
211
212
		return array();
213
	}
214
215
	function update_sent_progress_action( $actions ) {
216
217
		// quick way to map to first items with an array of arrays
218
		$actions_with_counts = array_count_values( array_filter( array_map( array( $this, 'get_action_name' ), $actions ) ) );
219
220
		if ( ! $this->is_started() || $this->is_finished() ) {
221
			return;
222
		}
223
224
		if ( isset( $actions_with_counts['jetpack_full_sync_start'] ) ) {
225
			$this->update_status_option( 'send_started', time() );
226
		}
227
228
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
229
			$module_actions     = $module->get_full_sync_actions();
230
			$status_option_name = "{$module->name()}_sent";
231
			$items_sent         = $this->get_status_option( $status_option_name, 0 );
232
233
			foreach ( $module_actions as $module_action ) {
234
				if ( isset( $actions_with_counts[ $module_action ] ) ) {
235
					$items_sent += $actions_with_counts[ $module_action ];
236
				}
237
			}
238
239
			if ( $items_sent > 0 ) {
240
				$this->update_status_option( $status_option_name, $items_sent );
241
			}
242
		}
243
244
		if ( isset( $actions_with_counts['jetpack_full_sync_end'] ) ) {
245
			$this->update_status_option( 'finished', time() );
246
		}
247
	}
248
249
	public function get_action_name( $queue_item ) {
250
		if ( is_array( $queue_item ) && isset( $queue_item[0] ) ) {
251
			return $queue_item[0];
252
		}
253
		return false;
254
	}
255
256
	public function is_started() {
257
		return ! ! $this->get_status_option( 'started' );
258
	}
259
260
	public function is_finished() {
261
		return ! ! $this->get_status_option( 'finished' );
262
	}
263
264
	public function get_status() {
265
		$status = array(
266
			'started'        => $this->get_status_option( 'started' ),
267
			'queue_finished' => $this->get_status_option( 'queue_finished' ),
268
			'send_started'   => $this->get_status_option( 'send_started' ),
269
			'finished'       => $this->get_status_option( 'finished' ),
270
			'sent'           => array(),
271
			'queue'          => array(),
272
			'config'         => $this->get_status_option( 'params' ),
273
			'total'          => array(),
274
		);
275
276
		$enqueue_status = $this->get_enqueue_status();
277
278
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
279
			$name = $module->name();
280
281
			if ( ! isset( $enqueue_status[ $name ] ) ) {
282
				continue;
283
			}
284
285
			list( $total, $queued, $state ) = $enqueue_status[ $name ];
0 ignored issues
show
Unused Code introduced by
The assignment to $state is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
286
287
			if ( $total ) {
288
				$status['total'][ $name ] = $total;
289
			}
290
291
			if ( $queued ) {
292
				$status['queue'][ $name ] = $queued;
293
			}
294
295
			if ( $sent = $this->get_status_option( "{$name}_sent" ) ) {
296
				$status['sent'][ $name ] = $sent;
297
			}
298
		}
299
300
		return $status;
301
	}
302
303
	public function clear_status() {
304
		$prefix = self::STATUS_OPTION_PREFIX;
305
		Jetpack_Options::delete_raw_option( "{$prefix}_started" );
306
		Jetpack_Options::delete_raw_option( "{$prefix}_params" );
307
		Jetpack_Options::delete_raw_option( "{$prefix}_queue_finished" );
308
		Jetpack_Options::delete_raw_option( "{$prefix}_send_started" );
309
		Jetpack_Options::delete_raw_option( "{$prefix}_finished" );
310
311
		$this->delete_enqueue_status();
312
313
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
314
			Jetpack_Options::delete_raw_option( "{$prefix}_{$module->name()}_sent" );
315
		}
316
	}
317
318
	public function reset_data() {
319
		$this->clear_status();
320
		$this->delete_config();
321
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
322
		$listener = Jetpack_Sync_Listener::get_instance();
323
		$listener->get_full_sync_queue()->reset();
324
	}
325
326
	private function get_status_option( $name, $default = null ) {
327
		$value = Jetpack_Options::get_raw_option( self::STATUS_OPTION_PREFIX . "_$name", $default );
328
329
		return is_numeric( $value ) ? intval( $value ) : $value;
330
	}
331
332
	private function update_status_option( $name, $value, $autoload = false ) {
333
		Jetpack_Options::update_raw_option( self::STATUS_OPTION_PREFIX . "_$name", $value, $autoload );
334
	}
335
336
	private function set_enqueue_status( $new_status ) {
337
		Jetpack_Options::update_raw_option( 'jetpack_sync_full_enqueue_status', $new_status );
338
	}
339
340
	private function delete_enqueue_status() {
341
		return Jetpack_Options::delete_raw_option( 'jetpack_sync_full_enqueue_status' );
342
	}
343
344
	private function get_enqueue_status() {
345
		return Jetpack_Options::get_raw_option( 'jetpack_sync_full_enqueue_status' );
346
	}
347
348
	private function set_config( $config ) {
349
		Jetpack_Options::update_raw_option( 'jetpack_sync_full_config', $config );
350
	}
351
352
	private function delete_config() {
353
		return Jetpack_Options::delete_raw_option( 'jetpack_sync_full_config' );
354
	}
355
356
	private function get_config() {
357
		return Jetpack_Options::get_raw_option( 'jetpack_sync_full_config' );
358
	}
359
360
	private function write_option( $name, $value ) {
361
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
362
		global $wpdb;
363
		$serialized_value = maybe_serialize( $value );
364
		// try updating, if no update then insert
365
		// TODO: try to deal with the fact that unchanged values can return updated_num = 0
366
		// below we used "insert ignore" to at least suppress the resulting error
367
		$updated_num = $wpdb->query(
368
			$wpdb->prepare(
369
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s",
370
				$serialized_value,
371
				$name
372
			)
373
		);
374
375
		if ( ! $updated_num ) {
376
			$updated_num = $wpdb->query(
377
				$wpdb->prepare(
378
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )",
379
					$name,
380
					$serialized_value
381
				)
382
			);
383
		}
384
		return $updated_num;
385
	}
386
387
	private function read_option( $name, $default = null ) {
388
		global $wpdb;
389
		$value = $wpdb->get_var(
390
			$wpdb->prepare(
391
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1",
392
				$name
393
			)
394
		);
395
		$value = maybe_unserialize( $value );
396
397
		if ( $value === null && $default !== null ) {
398
			return $default;
399
		}
400
401
		return $value;
402
	}
403
}
404