Completed
Push — fix/save-full-sync-status-duri... ( 75fbbc...7d2964 )
by
unknown
113:56 queued 102:46
created

Jetpack_Sync_Module_Full_Sync::start()   C

Complexity

Conditions 12
Paths 92

Size

Total Lines 72
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 33
nc 92
nop 1
dl 0
loc 72
rs 5.519
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 );
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->get_status_option( 'queue_finished' ) ) {
110
			return;
111
		}
112
113
		if ( ! $configs ) {
114
			$configs = $this->get_config();
115
		}
116
117
		if ( ! $enqueue_status ) {
118
			$enqueue_status = $this->get_enqueue_status();
119
		}
120
121
		$remaining_items_to_enqueue = Jetpack_Sync_Settings::get_setting( 'max_enqueue_full_sync' );
122
123
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
124
			$module_name = $module->name();
125
126
			// skip module if not configured for this sync or module is done
127
			if ( ! isset( $configs[ $module_name ] ) 
128
				|| // no module config
129
					! $configs[ $module_name ] 
130
				|| // no enqueue status
131
					! $enqueue_status[ $module_name ] 
132
				|| // finished enqueuing
133
					true === $enqueue_status[ $module_name ][ 2 ] ) {
134
				continue;
135
			}
136
137
			list( $items_enqueued, $next_enqueue_state ) = $module->enqueue_full_sync_actions( $configs[ $module_name ], $remaining_items_to_enqueue, $enqueue_status[ $module_name ][ 2 ] );
138
139
			$enqueue_status[ $module_name ][ 2 ] = $next_enqueue_state;
140
141
			// if items were processed, subtract them from the limit
142
			if ( ! is_null( $items_enqueued ) && $items_enqueued > 0 ) {
143
				$enqueue_status[ $module_name ][ 1 ] += $items_enqueued;
144
				$remaining_items_to_enqueue -= $items_enqueued;
145
			}
146
147
			if ( 0 >= $remaining_items_to_enqueue ) {
148
				// drop out, we're not allowed to process more items than this
149
				$this->set_enqueue_status( $enqueue_status );
150
				return;
151
			}
152
		}
153
		
154
		$this->set_enqueue_status( $enqueue_status );
155
		$this->update_status_option( 'queue_finished', time() );
156
157
		/**
158
		 * Fires when a full sync ends. This action is serialized
159
		 * and sent to the server with checksums so that we can confirm the
160
		 * sync was successful.
161
		 *
162
		 * @since 4.2.0
163
		 */
164
		do_action( 'jetpack_full_sync_end', '' );
165
	}
166
167
	function update_sent_progress_action( $actions ) {
168
169
		// quick way to map to first items with an array of arrays
170
		$actions_with_counts = array_count_values( array_filter( array_map( array( $this, 'get_action_name' ), $actions ) ) );
171
172
		if ( ! $this->is_started() || $this->is_finished() ) {
173
			return;
174
		}
175
176
		if ( isset( $actions_with_counts['jetpack_full_sync_start'] ) ) {
177
			$this->update_status_option( 'send_started', time() );
178
		}
179
180
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
181
			$module_actions     = $module->get_full_sync_actions();
182
			$status_option_name = "{$module->name()}_sent";
183
			$items_sent         = $this->get_status_option( $status_option_name, 0 );
184
185
			foreach ( $module_actions as $module_action ) {
186
				if ( isset( $actions_with_counts[ $module_action ] ) ) {
187
					$items_sent += $actions_with_counts[ $module_action ];
188
				}
189
			}
190
191
			if ( $items_sent > 0 ) {
192
				$this->update_status_option( $status_option_name, $items_sent );
193
			}	
194
		}
195
196
		if ( isset( $actions_with_counts['jetpack_full_sync_end'] ) ) {
197
			$this->update_status_option( 'finished', time() );
198
		}
199
	}
200
201
	public function get_action_name( $queue_item ) {
202
		if ( is_array( $queue_item ) && isset( $queue_item[0] ) ) {
203
			return $queue_item[0];
204
		}
205
		return false;
206
	}
207
208
	public function is_started() {
209
		return !! $this->get_status_option( 'started' );
210
	}
211
212
	public function is_finished() {
213
		return !! $this->get_status_option( 'finished' );
214
	}
215
216
	public function get_status() {
217
		$status = array(
218
			'started'        => $this->get_status_option( 'started' ),
219
			'queue_finished' => $this->get_status_option( 'queue_finished' ),
220
			'send_started'   => $this->get_status_option( 'send_started' ),
221
			'finished'       => $this->get_status_option( 'finished' ),
222
			'sent'           => array(),
223
			'queue'          => array(),
224
			'config'         => $this->get_status_option( 'params' ),
225
			'total'          => array(),
226
		);
227
228
		$enqueue_status = $this->get_enqueue_status();
229
		$module_config = $this->get_config();
0 ignored issues
show
Unused Code introduced by
$module_config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
230
231
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
232
			$name = $module->name();
233
234
			if ( ! isset( $enqueue_status[ $name ] ) ) {
235
				continue;
236
			}
237
238
			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...
239
240
			if ( $total ) {
241
				$status[ 'total' ][ $name ] = $total;
242
			}
243
244
			if ( $queued ) {
245
				$status[ 'queue' ][ $name ] = $queued;
246
			}
247
			
248
			if ( $sent = $this->get_status_option( "{$name}_sent" ) ) {
249
				$status[ 'sent' ][ $name ] = $sent;
250
			}
251
		}
252
253
		return $status;
254
	}
255
256
	public function clear_status() {		
257
		$prefix = self::STATUS_OPTION_PREFIX;		
258
		delete_option( "{$prefix}_started" );
259
		delete_option( "{$prefix}_params" );
260
		delete_option( "{$prefix}_queue_finished" );		
261
		delete_option( "{$prefix}_send_started" );		
262
		delete_option( "{$prefix}_finished" );		
263
		
264
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
265
			delete_option( "{$prefix}_{$module->name()}_sent" );		
266
		}
267
	}
268
269
	public function reset_data() {
270
		$this->clear_status();
271
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
272
		$listener = Jetpack_Sync_Listener::get_instance();
273
		$listener->get_full_sync_queue()->reset();
274
	}
275
276
	private function get_status_option( $name, $default = null ) {
277
		$prefix = self::STATUS_OPTION_PREFIX;
278
279
		$value = get_option( "{$prefix}_{$name}", $default );
280
		
281
		if ( ! $value ) {
282
			// don't cast to int if we didn't find a value - we want to preserve null or false as sentinals
283
			return $default;
284
		}
285
286
		return is_numeric( $value ) ? intval( $value ) : $value;
287
	}
288
289
	private function update_status_option( $name, $value ) {
290
		$prefix = self::STATUS_OPTION_PREFIX;
291
		update_option( "{$prefix}_{$name}", $value, false );
292
	}
293
294
	private function set_enqueue_status( $new_status ) {
295
		$this->write_option( 'jetpack_sync_full_enqueue_status', $new_status );
296
	}
297
298
	private function get_enqueue_status() {
299
		return $this->read_option( 'jetpack_sync_full_enqueue_status' );
300
	}
301
302
	private function set_config( $config ) {
303
		$this->write_option( 'jetpack_sync_full_config', $config );
304
	}
305
	
306
	private function get_config() {
307
		return $this->read_option( 'jetpack_sync_full_config' );
308
	}
309
310
	private function write_option( $name, $value ) {
311
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
312
		global $wpdb;
313
		$serialized_value = maybe_serialize( $value );
314
		// try updating, if no update then insert
315
		// TODO: try to deal with the fact that unchanged values can return updated_num = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
316
		// below we used "insert ignore" to at least suppress the resulting error
317
		$updated_num = $wpdb->query(
318
			$wpdb->prepare(
319
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s", 
320
				$serialized_value,
321
				$name
322
			)
323
		);
324
325
		if ( ! $updated_num ) {
326
			$updated_num = $wpdb->query(
327
				$wpdb->prepare(
328
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", 
329
					$name,
330
					$serialized_value
331
				)
332
			);
333
		}
334
		return $updated_num;
335
	}
336
337
	private function read_option( $name, $default = null ) {
338
		global $wpdb;
339
		$value = $wpdb->get_var( 
340
			$wpdb->prepare(
341
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", 
342
				$name
343
			)
344
		);
345
		$value = maybe_unserialize( $value );
346
347
		if ( $value === null && $default !== null ) {
348
			return $default;
349
		}
350
351
		return $value;
352
	}
353
}
354