Completed
Push — update/wp-55-autoupdate ( 3add47...edccb1 )
by
unknown
07:48
created

Sender   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 848
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 11

Importance

Changes 0
Metric Value
dl 0
loc 848
rs 1.752
c 0
b 0
f 0
wmc 86
lcom 3
cbo 11

38 Methods

Rating   Name   Duplication   Size   Complexity  
A get_instance() 0 7 2
A __construct() 0 4 1
A init() 0 8 2
A maybe_set_user_from_token() 0 12 5
A maybe_clear_user_from_token() 0 5 2
A get_next_sync_time() 0 3 1
A set_next_sync_time() 0 3 1
A do_full_sync() 0 10 3
A continue_full_sync_enqueue() 0 13 4
A do_sync() 0 3 1
B do_sync_and_set_delays() 0 39 9
B get_items_to_send() 0 47 8
A fastcgi_finish_request() 0 5 3
D do_sync_for_queue() 0 103 16
A send_action() 0 25 2
A create_action_to_send() 0 11 1
A sync_object() 0 9 1
A register_jetpack_xmlrpc_methods() 0 4 1
A get_sync_queue() 0 3 1
A get_full_sync_queue() 0 3 1
A get_codec() 0 3 1
A set_codec() 0 7 2
A send_checksum() 0 4 1
A reset_sync_queue() 0 3 1
A reset_full_sync_queue() 0 3 1
A set_dequeue_max_bytes() 0 3 1
A set_upload_max_bytes() 0 3 1
A set_upload_max_rows() 0 3 1
A set_sync_wait_time() 0 3 1
A get_sync_wait_time() 0 3 1
A set_enqueue_wait_time() 0 3 1
A get_enqueue_wait_time() 0 3 1
A set_sync_wait_threshold() 0 3 1
A get_sync_wait_threshold() 0 3 1
A set_max_dequeue_time() 0 3 1
A set_defaults() 0 16 1
A reset_data() 0 14 3
A uninstall() 0 11 1

How to fix   Complexity   

Complex Class

Complex classes like Sender 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 Sender, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Sync sender.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync;
9
10
use Automattic\Jetpack\Connection\Manager;
11
use Automattic\Jetpack\Constants;
12
13
/**
14
 * This class grabs pending actions from the queue and sends them
15
 */
16
class Sender {
17
	/**
18
	 * Name of the option that stores the time of the next sync.
19
	 *
20
	 * @access public
21
	 *
22
	 * @var string
23
	 */
24
	const NEXT_SYNC_TIME_OPTION_NAME = 'jetpack_next_sync_time';
25
26
	/**
27
	 * Sync timeout after a WPCOM error.
28
	 *
29
	 * @access public
30
	 *
31
	 * @var int
32
	 */
33
	const WPCOM_ERROR_SYNC_DELAY = 60;
34
35
	/**
36
	 * Sync timeout after a queue has been locked.
37
	 *
38
	 * @access public
39
	 *
40
	 * @var int
41
	 */
42
	const QUEUE_LOCKED_SYNC_DELAY = 10;
43
44
	/**
45
	 * Maximum bytes to checkout without exceeding the memory limit.
46
	 *
47
	 * @access private
48
	 *
49
	 * @var int
50
	 */
51
	private $dequeue_max_bytes;
52
53
	/**
54
	 * Maximum bytes in a single encoded item.
55
	 *
56
	 * @access private
57
	 *
58
	 * @var int
59
	 */
60
	private $upload_max_bytes;
61
62
	/**
63
	 * Maximum number of sync items in a single action.
64
	 *
65
	 * @access private
66
	 *
67
	 * @var int
68
	 */
69
	private $upload_max_rows;
70
71
	/**
72
	 * Maximum time for perfirming a checkout of items from the queue (in seconds).
73
	 *
74
	 * @access private
75
	 *
76
	 * @var int
77
	 */
78
	private $max_dequeue_time;
79
80
	/**
81
	 * How many seconds to wait after sending sync items after exceeding the sync wait threshold (in seconds).
82
	 *
83
	 * @access private
84
	 *
85
	 * @var int
86
	 */
87
	private $sync_wait_time;
88
89
	/**
90
	 * How much maximum time to wait for the checkout to finish (in seconds).
91
	 *
92
	 * @access private
93
	 *
94
	 * @var int
95
	 */
96
	private $sync_wait_threshold;
97
98
	/**
99
	 * How much maximum time to wait for the sync items to be queued for sending (in seconds).
100
	 *
101
	 * @access private
102
	 *
103
	 * @var int
104
	 */
105
	private $enqueue_wait_time;
106
107
	/**
108
	 * Incremental sync queue object.
109
	 *
110
	 * @access private
111
	 *
112
	 * @var Automattic\Jetpack\Sync\Queue
113
	 */
114
	private $sync_queue;
115
116
	/**
117
	 * Full sync queue object.
118
	 *
119
	 * @access private
120
	 *
121
	 * @var Automattic\Jetpack\Sync\Queue
122
	 */
123
	private $full_sync_queue;
124
125
	/**
126
	 * Codec object for encoding and decoding sync items.
127
	 *
128
	 * @access private
129
	 *
130
	 * @var Automattic\Jetpack\Sync\Codec_Interface
131
	 */
132
	private $codec;
133
134
	/**
135
	 * The current user before we change or clear it.
136
	 *
137
	 * @access private
138
	 *
139
	 * @var \WP_User
140
	 */
141
	private $old_user;
142
143
	/**
144
	 * Container for the singleton instance of this class.
145
	 *
146
	 * @access private
147
	 * @static
148
	 *
149
	 * @var Automattic\Jetpack\Sync\Sender
150
	 */
151
	private static $instance;
152
153
	/**
154
	 * Retrieve the singleton instance of this class.
155
	 *
156
	 * @access public
157
	 * @static
158
	 *
159
	 * @return Sender
160
	 */
161
	public static function get_instance() {
162
		if ( null === self::$instance ) {
163
			self::$instance = new self();
0 ignored issues
show
Documentation Bug introduced by
It seems like new self() of type object<Automattic\Jetpack\Sync\Sender> is incompatible with the declared type object<Automattic\Jetpac...ic\Jetpack\Sync\Sender> of property $instance.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
164
		}
165
166
		return self::$instance;
167
	}
168
169
	/**
170
	 * Constructor.
171
	 * This is necessary because you can't use "new" when you declare instance properties >:(
172
	 *
173
	 * @access protected
174
	 * @static
175
	 */
176
	protected function __construct() {
177
		$this->set_defaults();
178
		$this->init();
179
	}
180
181
	/**
182
	 * Initialize the sender.
183
	 * Prepares the current user and initializes all sync modules.
184
	 *
185
	 * @access private
186
	 */
187
	private function init() {
188
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_set_user_from_token' ), 1 );
189
		add_action( 'jetpack_sync_before_send_queue_sync', array( $this, 'maybe_clear_user_from_token' ), 20 );
190
		add_filter( 'jetpack_xmlrpc_methods', array( $this, 'register_jetpack_xmlrpc_methods' ) );
191
		foreach ( Modules::get_modules() as $module ) {
192
			$module->init_before_send();
193
		}
194
	}
195
196
	/**
197
	 * Detect if this is a XMLRPC request with a valid signature.
198
	 * If so, changes the user to the new one.
199
	 *
200
	 * @access public
201
	 */
202
	public function maybe_set_user_from_token() {
203
		$connection    = new Manager();
204
		$verified_user = $connection->verify_xml_rpc_signature();
205
		if ( Constants::is_true( 'XMLRPC_REQUEST' ) &&
206
			! is_wp_error( $verified_user )
207
			&& $verified_user
208
		) {
209
			$old_user       = wp_get_current_user();
210
			$this->old_user = isset( $old_user->ID ) ? $old_user->ID : 0;
211
			wp_set_current_user( $verified_user['user_id'] );
212
		}
213
	}
214
215
	/**
216
	 * If we used to have a previous current user, revert back to it.
217
	 *
218
	 * @access public
219
	 */
220
	public function maybe_clear_user_from_token() {
221
		if ( isset( $this->old_user ) ) {
222
			wp_set_current_user( $this->old_user );
223
		}
224
	}
225
226
	/**
227
	 * Retrieve the next sync time.
228
	 *
229
	 * @access public
230
	 *
231
	 * @param string $queue_name Name of the queue.
232
	 * @return float Timestamp of the next sync.
233
	 */
234
	public function get_next_sync_time( $queue_name ) {
235
		return (float) get_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, 0 );
236
	}
237
238
	/**
239
	 * Set the next sync time.
240
	 *
241
	 * @access public
242
	 *
243
	 * @param int    $time       Timestamp of the next sync.
244
	 * @param string $queue_name Name of the queue.
245
	 * @return boolean True if update was successful, false otherwise.
246
	 */
247
	public function set_next_sync_time( $time, $queue_name ) {
248
		return update_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name, $time, true );
249
	}
250
251
	/**
252
	 * Trigger a full sync.
253
	 *
254
	 * @access public
255
	 *
256
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
257
	 */
258
	public function do_full_sync() {
259
		if ( ! Modules::get_module( 'full-sync' ) ) {
260
			return;
261
		}
262
		if ( ! Settings::get_setting( 'full_sync_sender_enabled' ) ) {
263
			return;
264
		}
265
		$this->continue_full_sync_enqueue();
266
		return $this->do_sync_and_set_delays( $this->full_sync_queue );
267
	}
268
269
	/**
270
	 * Enqueue the next sync items for sending.
271
	 * Will not be done if the current request is a WP import one.
272
	 * Will be delayed until the next sync time comes.
273
	 *
274
	 * @access private
275
	 */
276
	private function continue_full_sync_enqueue() {
277
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
278
			return false;
279
		}
280
281
		if ( $this->get_next_sync_time( 'full-sync-enqueue' ) > microtime( true ) ) {
282
			return false;
283
		}
284
285
		Modules::get_module( 'full-sync' )->continue_enqueuing();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Automattic\Jetpack\Sync\Modules\Module as the method continue_enqueuing() does only exist in the following sub-classes of Automattic\Jetpack\Sync\Modules\Module: Automattic\Jetpack\Sync\Modules\Full_Sync, Automattic\Jetpack\Sync\...s\Full_Sync_Immediately. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
286
287
		$this->set_next_sync_time( time() + $this->get_enqueue_wait_time(), 'full-sync-enqueue' );
288
	}
289
290
	/**
291
	 * Trigger incremental sync.
292
	 *
293
	 * @access public
294
	 *
295
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
296
	 */
297
	public function do_sync() {
298
		return $this->do_sync_and_set_delays( $this->sync_queue );
299
	}
300
301
	/**
302
	 * Trigger sync for a certain sync queue.
303
	 * Responsible for setting next sync time.
304
	 * Will not be delayed if the current request is a WP import one.
305
	 * Will be delayed until the next sync time comes.
306
	 *
307
	 * @access public
308
	 *
309
	 * @param Automattic\Jetpack\Sync\Queue $queue Queue object.
310
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
311
	 */
312
	public function do_sync_and_set_delays( $queue ) {
313
		// Don't sync if importing.
314
		if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
315
			return new \WP_Error( 'is_importing' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'is_importing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
316
		}
317
318
		if ( ! Settings::is_sender_enabled( $queue->id ) ) {
319
			return new \WP_Error( 'sender_disabled_for_queue_' . $queue->id );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'sender_disabled_for_queue_' . $queue->id.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
320
		}
321
322
		// Don't sync if we are throttled.
323
		if ( $this->get_next_sync_time( $queue->id ) > microtime( true ) ) {
324
			return new \WP_Error( 'sync_throttled' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'sync_throttled'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
325
		}
326
327
		$start_time = microtime( true );
328
329
		Settings::set_is_syncing( true );
330
331
		$sync_result = $this->do_sync_for_queue( $queue );
332
333
		Settings::set_is_syncing( false );
334
335
		$exceeded_sync_wait_threshold = ( microtime( true ) - $start_time ) > (float) $this->get_sync_wait_threshold();
336
337
		if ( is_wp_error( $sync_result ) ) {
338
			if ( 'unclosed_buffer' === $sync_result->get_error_code() ) {
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
339
				$this->set_next_sync_time( time() + self::QUEUE_LOCKED_SYNC_DELAY, $queue->id );
340
			}
341
			if ( 'wpcom_error' === $sync_result->get_error_code() ) {
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
342
				$this->set_next_sync_time( time() + self::WPCOM_ERROR_SYNC_DELAY, $queue->id );
343
			}
344
		} elseif ( $exceeded_sync_wait_threshold ) {
345
			// If we actually sent data and it took a while, wait before sending again.
346
			$this->set_next_sync_time( time() + $this->get_sync_wait_time(), $queue->id );
347
		}
348
349
		return $sync_result;
350
	}
351
352
	/**
353
	 * Retrieve the next sync items to send.
354
	 *
355
	 * @access public
356
	 *
357
	 * @param (array|Automattic\Jetpack\Sync\Queue_Buffer) $buffer_or_items Queue buffer or array of objects.
358
	 * @param boolean                                      $encode Whether to encode the items.
359
	 * @return array Sync items to send.
360
	 */
361
	public function get_items_to_send( $buffer_or_items, $encode = true ) {
362
		// Track how long we've been processing so we can avoid request timeouts.
363
		$start_time    = microtime( true );
364
		$upload_size   = 0;
365
		$items_to_send = array();
366
		$items         = is_array( $buffer_or_items ) ? $buffer_or_items : $buffer_or_items->get_items();
367
		// Set up current screen to avoid errors rendering content.
368
		require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
369
		require_once ABSPATH . 'wp-admin/includes/screen.php';
370
		set_current_screen( 'sync' );
371
		$skipped_items_ids = array();
372
		/**
373
		 * We estimate the total encoded size as we go by encoding each item individually.
374
		 * This is expensive, but the only way to really know :/
375
		 */
376
		foreach ( $items as $key => $item ) {
377
			// Suspending cache addition help prevent overloading in memory cache of large sites.
378
			wp_suspend_cache_addition( true );
379
			/**
380
			 * Modify the data within an action before it is serialized and sent to the server
381
			 * For example, during full sync this expands Post ID's into full Post objects,
382
			 * so that we don't have to serialize the whole object into the queue.
383
			 *
384
			 * @since 4.2.0
385
			 *
386
			 * @param array The action parameters
387
			 * @param int The ID of the user who triggered the action
388
			 */
389
			$item[1] = apply_filters( 'jetpack_sync_before_send_' . $item[0], $item[1], $item[2] );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $item[2].

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
390
			wp_suspend_cache_addition( false );
391
			if ( false === $item[1] ) {
392
				$skipped_items_ids[] = $key;
393
				continue;
394
			}
395
			$encoded_item = $encode ? $this->codec->encode( $item ) : $item;
396
			$upload_size += strlen( $encoded_item );
397
			if ( $upload_size > $this->upload_max_bytes && count( $items_to_send ) > 0 ) {
398
				break;
399
			}
400
			$items_to_send[ $key ] = $encoded_item;
401
			if ( microtime( true ) - $start_time > $this->max_dequeue_time ) {
402
				break;
403
			}
404
		}
405
406
		return array( $items_to_send, $skipped_items_ids, $items, microtime( true ) - $start_time );
407
	}
408
409
	/**
410
	 * If supported, flush all response data to the client and finish the request.
411
	 * This allows for time consuming tasks to be performed without leaving the connection open.
412
	 *
413
	 * @access private
414
	 */
415
	private function fastcgi_finish_request() {
416
		if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
417
			fastcgi_finish_request();
418
		}
419
	}
420
421
	/**
422
	 * Perform sync for a certain sync queue.
423
	 *
424
	 * @access public
425
	 *
426
	 * @param Automattic\Jetpack\Sync\Queue $queue Queue object.
427
	 * @return boolean|\WP_Error True if this sync sending was successful, error object otherwise.
428
	 */
429
	public function do_sync_for_queue( $queue ) {
430
		do_action( 'jetpack_sync_before_send_queue_' . $queue->id );
431
		if ( $queue->size() === 0 ) {
432
			return new \WP_Error( 'empty_queue_' . $queue->id );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_queue_' . $queue->id.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
433
		}
434
435
		/**
436
		 * Now that we're sure we are about to sync, try to ignore user abort
437
		 * so we can avoid getting into a bad state.
438
		 */
439
		if ( function_exists( 'ignore_user_abort' ) ) {
440
			ignore_user_abort( true );
441
		}
442
443
		/* Don't make the request block till we finish, if possible. */
444
		if ( Constants::is_true( 'REST_REQUEST' ) || Constants::is_true( 'XMLRPC_REQUEST' ) ) {
445
			$this->fastcgi_finish_request();
446
		}
447
448
		$checkout_start_time = microtime( true );
449
450
		$buffer = $queue->checkout_with_memory_limit( $this->dequeue_max_bytes, $this->upload_max_rows );
451
452
		if ( ! $buffer ) {
453
			// Buffer has no items.
454
			return new \WP_Error( 'empty_buffer' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_buffer'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
455
		}
456
457
		if ( is_wp_error( $buffer ) ) {
458
			return $buffer;
459
		}
460
461
		$checkout_duration = microtime( true ) - $checkout_start_time;
462
463
		list( $items_to_send, $skipped_items_ids, $items, $preprocess_duration ) = $this->get_items_to_send( $buffer, true );
464
		if ( ! empty( $items_to_send ) ) {
465
			/**
466
			 * Fires when data is ready to send to the server.
467
			 * Return false or WP_Error to abort the sync (e.g. if there's an error)
468
			 * The items will be automatically re-sent later
469
			 *
470
			 * @since 4.2.0
471
			 *
472
			 * @param array  $data The action buffer
473
			 * @param string $codec The codec name used to encode the data
474
			 * @param double $time The current time
475
			 * @param string $queue The queue used to send ('sync' or 'full_sync')
476
			 * @param float  $checkout_duration The duration of the checkout operation.
477
			 * @param float  $preprocess_duration The duration of the pre-process operation.
478
			 * @param int    $queue_size The size of the sync queue at the time of processing.
479
			 */
480
			Settings::set_is_sending( true );
481
			$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->codec->name(), microtime( true ), $queue->id, $checkout_duration, $preprocess_duration, $queue->size(), $buffer->id );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this->codec->name().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
482
			Settings::set_is_sending( false );
483
		} else {
484
			$processed_item_ids = $skipped_items_ids;
485
			$skipped_items_ids  = array();
486
		}
487
488
		if ( 'non-blocking' !== $processed_item_ids ) {
489
			if ( ! $processed_item_ids || is_wp_error( $processed_item_ids ) ) {
490
				$checked_in_item_ids = $queue->checkin( $buffer );
491
				if ( is_wp_error( $checked_in_item_ids ) ) {
492
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
493
					error_log( 'Error checking in buffer: ' . $checked_in_item_ids->get_error_message() );
494
					$queue->force_checkin();
495
				}
496
				if ( is_wp_error( $processed_item_ids ) ) {
497
					return new \WP_Error( 'wpcom_error', $processed_item_ids->get_error_code() );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
498
				}
499
500
				// Returning a wpcom_error is a sign to the caller that we should wait a while before syncing again.
501
				return new \WP_Error( 'wpcom_error', 'jetpack_sync_send_data_false' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
502
			} else {
503
				// Detect if the last item ID was an error.
504
				$had_wp_error = is_wp_error( end( $processed_item_ids ) );
505
				if ( $had_wp_error ) {
506
					$wp_error = array_pop( $processed_item_ids );
507
				}
508
				// Also checkin any items that were skipped.
509
				if ( count( $skipped_items_ids ) > 0 ) {
510
					$processed_item_ids = array_merge( $processed_item_ids, $skipped_items_ids );
511
				}
512
				$processed_items = array_intersect_key( $items, array_flip( $processed_item_ids ) );
513
				/**
514
				 * Allows us to keep track of all the actions that have been sent.
515
				 * Allows us to calculate the progress of specific actions.
516
				 *
517
				 * @since 4.2.0
518
				 *
519
				 * @param array $processed_actions The actions that we send successfully.
520
				 */
521
				do_action( 'jetpack_sync_processed_actions', $processed_items );
522
				$queue->close( $buffer, $processed_item_ids );
523
				// Returning a WP_Error is a sign to the caller that we should wait a while before syncing again.
524
				if ( $had_wp_error ) {
525
					return new \WP_Error( 'wpcom_error', $wp_error->get_error_code() );
0 ignored issues
show
Bug introduced by
The variable $wp_error 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...
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
526
				}
527
			}
528
		}
529
530
		return true;
531
	}
532
533
	/**
534
	 * Immediately sends a single item without firing or enqueuing it
535
	 *
536
	 * @param string $action_name The action.
537
	 * @param array  $data The data associated with the action.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $data not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
538
	 *
539
	 * @return Items processed. TODO: this doesn't make much sense anymore, it should probably be just a bool.
540
	 */
541
	public function send_action( $action_name, $data = null ) {
542
		if ( ! Settings::is_sender_enabled( 'full_sync' ) ) {
543
			return array();
544
		}
545
546
		// Compose the data to be sent.
547
		$action_to_send = $this->create_action_to_send( $action_name, $data );
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 541 can also be of type null; however, Automattic\Jetpack\Sync\...create_action_to_send() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
548
549
		list( $items_to_send, $skipped_items_ids, $items, $preprocess_duration ) = $this->get_items_to_send( $action_to_send, true ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
0 ignored issues
show
Unused Code introduced by
The assignment to $skipped_items_ids 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...
Unused Code introduced by
The assignment to $items 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...
550
		Settings::set_is_sending( true );
551
		$processed_item_ids = apply_filters( 'jetpack_sync_send_data', $items_to_send, $this->get_codec()->name(), microtime( true ), 'immediate-send', 0, $preprocess_duration );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this->get_codec()->name().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
552
		Settings::set_is_sending( false );
553
554
		/**
555
		 * Allows us to keep track of all the actions that have been sent.
556
		 * Allows us to calculate the progress of specific actions.
557
		 *
558
		 * @param array $processed_actions The actions that we send successfully.
559
		 *
560
		 * @since 4.2.0
561
		 */
562
		do_action( 'jetpack_sync_processed_actions', $action_to_send );
563
564
		return $processed_item_ids;
565
	}
566
567
	/**
568
	 * Create an synthetic action for direct sending to WPCOM during full sync (for example)
569
	 *
570
	 * @access private
571
	 *
572
	 * @param string $action_name The action.
573
	 * @param array  $data The data associated with the action.
574
	 * @return array An array of synthetic sync actions keyed by current microtime(true)
575
	 */
576
	private function create_action_to_send( $action_name, $data ) {
577
		return array(
578
			(string) microtime( true ) => array(
579
				$action_name,
580
				$data,
581
				get_current_user_id(),
582
				microtime( true ),
583
				Settings::is_importing(),
584
			),
585
		);
586
	}
587
588
	/**
589
	 * Returns any object that is able to be synced.
590
	 *
591
	 * @access public
592
	 *
593
	 * @param array $args the synchronized object parameters.
594
	 * @return string Encoded sync object.
595
	 */
596
	public function sync_object( $args ) {
597
		// For example: posts, post, 5.
598
		list( $module_name, $object_type, $id ) = $args;
599
600
		$sync_module = Modules::get_module( $module_name );
601
		$codec       = $this->get_codec();
602
603
		return $codec->encode( $sync_module->get_object_by_id( $object_type, $id ) );
604
	}
605
606
	/**
607
	 * Register additional sync XML-RPC methods available to Jetpack for authenticated users.
608
	 *
609
	 * @access public
610
	 * @since 7.8
611
	 *
612
	 * @param array $jetpack_methods XML-RPC methods available to the Jetpack Server.
613
	 * @return array Filtered XML-RPC methods.
614
	 */
615
	public function register_jetpack_xmlrpc_methods( $jetpack_methods ) {
616
		$jetpack_methods['jetpack.syncObject'] = array( $this, 'sync_object' );
617
		return $jetpack_methods;
618
	}
619
620
	/**
621
	 * Get the incremental sync queue object.
622
	 *
623
	 * @access public
624
	 *
625
	 * @return Automattic\Jetpack\Sync\Queue Queue object.
626
	 */
627
	public function get_sync_queue() {
628
		return $this->sync_queue;
629
	}
630
631
	/**
632
	 * Get the full sync queue object.
633
	 *
634
	 * @access public
635
	 *
636
	 * @return Automattic\Jetpack\Sync\Queue Queue object.
637
	 */
638
	public function get_full_sync_queue() {
639
		return $this->full_sync_queue;
640
	}
641
642
	/**
643
	 * Get the codec object.
644
	 *
645
	 * @access public
646
	 *
647
	 * @return Automattic\Jetpack\Sync\Codec_Interface Codec object.
648
	 */
649
	public function get_codec() {
650
		return $this->codec;
651
	}
652
653
	/**
654
	 * Determine the codec object.
655
	 * Use gzip deflate if supported.
656
	 *
657
	 * @access public
658
	 */
659
	public function set_codec() {
660
		if ( function_exists( 'gzinflate' ) ) {
661
			$this->codec = new JSON_Deflate_Array_Codec();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\...N_Deflate_Array_Codec() of type object<Automattic\Jetpac...ON_Deflate_Array_Codec> is incompatible with the declared type object<Automattic\Jetpac...k\Sync\Codec_Interface> of property $codec.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
662
		} else {
663
			$this->codec = new Simple_Codec();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\Sync\Simple_Codec() of type object<Automattic\Jetpack\Sync\Simple_Codec> is incompatible with the declared type object<Automattic\Jetpac...k\Sync\Codec_Interface> of property $codec.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
664
		}
665
	}
666
667
	/**
668
	 * Compute and send all the checksums.
669
	 *
670
	 * @access public
671
	 */
672
	public function send_checksum() {
673
		$store = new Replicastore();
674
		do_action( 'jetpack_sync_checksum', $store->checksum_all() );
675
	}
676
677
	/**
678
	 * Reset the incremental sync queue.
679
	 *
680
	 * @access public
681
	 */
682
	public function reset_sync_queue() {
683
		$this->sync_queue->reset();
684
	}
685
686
	/**
687
	 * Reset the full sync queue.
688
	 *
689
	 * @access public
690
	 */
691
	public function reset_full_sync_queue() {
692
		$this->full_sync_queue->reset();
693
	}
694
695
	/**
696
	 * Set the maximum bytes to checkout without exceeding the memory limit.
697
	 *
698
	 * @access public
699
	 *
700
	 * @param int $size Maximum bytes to checkout.
701
	 */
702
	public function set_dequeue_max_bytes( $size ) {
703
		$this->dequeue_max_bytes = $size;
704
	}
705
706
	/**
707
	 * Set the maximum bytes in a single encoded item.
708
	 *
709
	 * @access public
710
	 *
711
	 * @param int $max_bytes Maximum bytes in a single encoded item.
712
	 */
713
	public function set_upload_max_bytes( $max_bytes ) {
714
		$this->upload_max_bytes = $max_bytes;
715
	}
716
717
	/**
718
	 * Set the maximum number of sync items in a single action.
719
	 *
720
	 * @access public
721
	 *
722
	 * @param int $max_rows Maximum number of sync items.
723
	 */
724
	public function set_upload_max_rows( $max_rows ) {
725
		$this->upload_max_rows = $max_rows;
726
	}
727
728
	/**
729
	 * Set the sync wait time (in seconds).
730
	 *
731
	 * @access public
732
	 *
733
	 * @param int $seconds Sync wait time.
734
	 */
735
	public function set_sync_wait_time( $seconds ) {
736
		$this->sync_wait_time = $seconds;
737
	}
738
739
	/**
740
	 * Get current sync wait time (in seconds).
741
	 *
742
	 * @access public
743
	 *
744
	 * @return int Sync wait time.
745
	 */
746
	public function get_sync_wait_time() {
747
		return $this->sync_wait_time;
748
	}
749
750
	/**
751
	 * Set the enqueue wait time (in seconds).
752
	 *
753
	 * @access public
754
	 *
755
	 * @param int $seconds Enqueue wait time.
756
	 */
757
	public function set_enqueue_wait_time( $seconds ) {
758
		$this->enqueue_wait_time = $seconds;
759
	}
760
761
	/**
762
	 * Get current enqueue wait time (in seconds).
763
	 *
764
	 * @access public
765
	 *
766
	 * @return int Enqueue wait time.
767
	 */
768
	public function get_enqueue_wait_time() {
769
		return $this->enqueue_wait_time;
770
	}
771
772
	/**
773
	 * Set the sync wait threshold (in seconds).
774
	 *
775
	 * @access public
776
	 *
777
	 * @param int $seconds Sync wait threshold.
778
	 */
779
	public function set_sync_wait_threshold( $seconds ) {
780
		$this->sync_wait_threshold = $seconds;
781
	}
782
783
	/**
784
	 * Get current sync wait threshold (in seconds).
785
	 *
786
	 * @access public
787
	 *
788
	 * @return int Sync wait threshold.
789
	 */
790
	public function get_sync_wait_threshold() {
791
		return $this->sync_wait_threshold;
792
	}
793
794
	/**
795
	 * Set the maximum time for perfirming a checkout of items from the queue (in seconds).
796
	 *
797
	 * @access public
798
	 *
799
	 * @param int $seconds Maximum dequeue time.
800
	 */
801
	public function set_max_dequeue_time( $seconds ) {
802
		$this->max_dequeue_time = $seconds;
803
	}
804
805
	/**
806
	 * Initialize the sync queues, codec and set the default settings.
807
	 *
808
	 * @access public
809
	 */
810
	public function set_defaults() {
811
		$this->sync_queue      = new Queue( 'sync' );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\Sync\Queue('sync') of type object<Automattic\Jetpack\Sync\Queue> is incompatible with the declared type object<Automattic\Jetpac...tic\Jetpack\Sync\Queue> of property $sync_queue.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
812
		$this->full_sync_queue = new Queue( 'full_sync' );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Automattic\Jetpack\Sync\Queue('full_sync') of type object<Automattic\Jetpack\Sync\Queue> is incompatible with the declared type object<Automattic\Jetpac...tic\Jetpack\Sync\Queue> of property $full_sync_queue.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
813
		$this->set_codec();
814
815
		// Saved settings.
816
		Settings::set_importing( null );
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
817
		$settings = Settings::get_settings();
818
		$this->set_dequeue_max_bytes( $settings['dequeue_max_bytes'] );
819
		$this->set_upload_max_bytes( $settings['upload_max_bytes'] );
820
		$this->set_upload_max_rows( $settings['upload_max_rows'] );
821
		$this->set_sync_wait_time( $settings['sync_wait_time'] );
822
		$this->set_enqueue_wait_time( $settings['enqueue_wait_time'] );
823
		$this->set_sync_wait_threshold( $settings['sync_wait_threshold'] );
824
		$this->set_max_dequeue_time( Defaults::get_max_sync_execution_time() );
825
	}
826
827
	/**
828
	 * Reset sync queues, modules and settings.
829
	 *
830
	 * @access public
831
	 */
832
	public function reset_data() {
833
		$this->reset_sync_queue();
834
		$this->reset_full_sync_queue();
835
836
		foreach ( Modules::get_modules() as $module ) {
837
			$module->reset_data();
838
		}
839
840
		foreach ( array( 'sync', 'full_sync', 'full-sync-enqueue' ) as $queue_name ) {
841
			delete_option( self::NEXT_SYNC_TIME_OPTION_NAME . '_' . $queue_name );
842
		}
843
844
		Settings::reset_data();
845
	}
846
847
	/**
848
	 * Perform cleanup at the event of plugin uninstallation.
849
	 *
850
	 * @access public
851
	 */
852
	public function uninstall() {
853
		// Lets delete all the other fun stuff like transient and option and the sync queue.
854
		$this->reset_data();
855
856
		// Delete the full sync status.
857
		delete_option( 'jetpack_full_sync_status' );
858
859
		// Clear the sync cron.
860
		wp_clear_scheduled_hook( 'jetpack_sync_cron' );
861
		wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
862
	}
863
}
864