Completed
Push — fix/small-images-og ( 927a25...456c02 )
by Jeremy
35:03 queued 25:43
created

Jetpack_Sync_Module_Full_Sync   C

Complexity

Total Complexity 66

Size/Duplication

Total Lines 352
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 66
lcom 1
cbo 6
dl 0
loc 352
rs 5.7474
c 0
b 0
f 0

22 Methods

Rating   Name   Duplication   Size   Complexity  
D update_sent_progress_action() 0 33 9
A get_action_name() 0 6 3
A is_started() 0 3 1
A is_finished() 0 3 1
A set_enqueue_status() 0 3 1
A name() 0 3 1
A init_full_sync_listeners() 0 6 1
A init_before_send() 0 4 1
C start() 0 72 12
C continue_enqueuing() 0 69 14
A get_status_option() 0 5 2
A update_status_option() 0 3 1
B get_status() 0 38 6
A clear_status() 0 14 2
A reset_data() 0 7 1
A delete_enqueue_status() 0 3 1
A get_enqueue_status() 0 3 1
A set_config() 0 3 1
A delete_config() 0 3 1
A get_config() 0 3 1
B write_option() 0 26 2
A read_option() 0 16 3

How to fix   Complexity   

Complex Class

Complex classes like Jetpack_Sync_Module_Full_Sync often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Sync_Module_Full_Sync, and based on these observations, apply Extract Interface, too.

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->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
		/**
170
		 * Fires when a full sync ends. This action is serialized
171
		 * and sent to the server.
172
		 *
173
		 * @since 4.2.0
174
		 */
175
		do_action( 'jetpack_full_sync_end', '' );
176
	}
177
178
	function update_sent_progress_action( $actions ) {
179
180
		// quick way to map to first items with an array of arrays
181
		$actions_with_counts = array_count_values( array_filter( array_map( array( $this, 'get_action_name' ), $actions ) ) );
182
183
		if ( ! $this->is_started() || $this->is_finished() ) {
184
			return;
185
		}
186
187
		if ( isset( $actions_with_counts['jetpack_full_sync_start'] ) ) {
188
			$this->update_status_option( 'send_started', time() );
189
		}
190
191
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
192
			$module_actions     = $module->get_full_sync_actions();
193
			$status_option_name = "{$module->name()}_sent";
194
			$items_sent         = $this->get_status_option( $status_option_name, 0 );
195
196
			foreach ( $module_actions as $module_action ) {
197
				if ( isset( $actions_with_counts[ $module_action ] ) ) {
198
					$items_sent += $actions_with_counts[ $module_action ];
199
				}
200
			}
201
202
			if ( $items_sent > 0 ) {
203
				$this->update_status_option( $status_option_name, $items_sent );
204
			}
205
		}
206
207
		if ( isset( $actions_with_counts['jetpack_full_sync_end'] ) ) {
208
			$this->update_status_option( 'finished', time() );
209
		}
210
	}
211
212
	public function get_action_name( $queue_item ) {
213
		if ( is_array( $queue_item ) && isset( $queue_item[0] ) ) {
214
			return $queue_item[0];
215
		}
216
		return false;
217
	}
218
219
	public function is_started() {
220
		return !! $this->get_status_option( 'started' );
221
	}
222
223
	public function is_finished() {
224
		return !! $this->get_status_option( 'finished' );
225
	}
226
227
	public function get_status() {
228
		$status = array(
229
			'started'        => $this->get_status_option( 'started' ),
230
			'queue_finished' => $this->get_status_option( 'queue_finished' ),
231
			'send_started'   => $this->get_status_option( 'send_started' ),
232
			'finished'       => $this->get_status_option( 'finished' ),
233
			'sent'           => array(),
234
			'queue'          => array(),
235
			'config'         => $this->get_status_option( 'params' ),
236
			'total'          => array(),
237
		);
238
239
		$enqueue_status = $this->get_enqueue_status();
240
241
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
242
			$name = $module->name();
243
244
			if ( ! isset( $enqueue_status[ $name ] ) ) {
245
				continue;
246
			}
247
248
			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...
249
250
			if ( $total ) {
251
				$status[ 'total' ][ $name ] = $total;
252
			}
253
254
			if ( $queued ) {
255
				$status[ 'queue' ][ $name ] = $queued;
256
			}
257
258
			if ( $sent = $this->get_status_option( "{$name}_sent" ) ) {
259
				$status[ 'sent' ][ $name ] = $sent;
260
			}
261
		}
262
263
		return $status;
264
	}
265
266
	public function clear_status() {
267
		$prefix = self::STATUS_OPTION_PREFIX;
268
		Jetpack_Options::delete_raw_option( "{$prefix}_started" );
269
		Jetpack_Options::delete_raw_option( "{$prefix}_params" );
270
		Jetpack_Options::delete_raw_option( "{$prefix}_queue_finished" );
271
		Jetpack_Options::delete_raw_option( "{$prefix}_send_started" );
272
		Jetpack_Options::delete_raw_option( "{$prefix}_finished" );
273
274
		$this->delete_enqueue_status();
275
276
		foreach ( Jetpack_Sync_Modules::get_modules() as $module ) {
277
			Jetpack_Options::delete_raw_option( "{$prefix}_{$module->name()}_sent" );
278
		}
279
	}
280
281
	public function reset_data() {
282
		$this->clear_status();
283
		$this->delete_config();
284
		require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
285
		$listener = Jetpack_Sync_Listener::get_instance();
286
		$listener->get_full_sync_queue()->reset();
287
	}
288
289
	private function get_status_option( $name, $default = null ) {
290
		$value = Jetpack_Options::get_raw_option( self::STATUS_OPTION_PREFIX . "_$name", $default );
291
292
		return is_numeric( $value ) ? intval( $value ) : $value;
293
	}
294
295
	private function update_status_option( $name, $value, $autoload = false ) {
296
		Jetpack_Options::update_raw_option( self::STATUS_OPTION_PREFIX . "_$name", $value, $autoload );
297
	}
298
299
	private function set_enqueue_status( $new_status ) {
300
		Jetpack_Options::update_raw_option( 'jetpack_sync_full_enqueue_status', $new_status );
301
	}
302
303
	private function delete_enqueue_status() {
304
		return Jetpack_Options::delete_raw_option( 'jetpack_sync_full_enqueue_status' );
305
	}
306
307
	private function get_enqueue_status() {
308
		return Jetpack_Options::get_raw_option( 'jetpack_sync_full_enqueue_status' );
309
	}
310
311
	private function set_config( $config ) {
312
		Jetpack_Options::update_raw_option( 'jetpack_sync_full_config', $config );
313
	}
314
315
	private function delete_config() {
316
		return Jetpack_Options::delete_raw_option( 'jetpack_sync_full_config' );
317
	}
318
319
	private function get_config() {
320
		return Jetpack_Options::get_raw_option( 'jetpack_sync_full_config' );
321
	}
322
323
	private function write_option( $name, $value ) {
324
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
325
		global $wpdb;
326
		$serialized_value = maybe_serialize( $value );
327
		// try updating, if no update then insert
328
		// 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...
329
		// below we used "insert ignore" to at least suppress the resulting error
330
		$updated_num = $wpdb->query(
331
			$wpdb->prepare(
332
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s",
333
				$serialized_value,
334
				$name
335
			)
336
		);
337
338
		if ( ! $updated_num ) {
339
			$updated_num = $wpdb->query(
340
				$wpdb->prepare(
341
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )",
342
					$name,
343
					$serialized_value
344
				)
345
			);
346
		}
347
		return $updated_num;
348
	}
349
350
	private function read_option( $name, $default = null ) {
351
		global $wpdb;
352
		$value = $wpdb->get_var(
353
			$wpdb->prepare(
354
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1",
355
				$name
356
			)
357
		);
358
		$value = maybe_unserialize( $value );
359
360
		if ( $value === null && $default !== null ) {
361
			return $default;
362
		}
363
364
		return $value;
365
	}
366
}
367