Completed
Push — add/sync-rest-2 ( 909866...c17d34 )
by
unknown
44:13 queued 34:51
created

Jetpack_Sync_Client::init()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 55
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 13
Bugs 1 Features 3
Metric Value
c 13
b 1
f 3
dl 0
loc 55
rs 9.078
cc 4
eloc 24
nc 6
nop 0

How to fix   Long Method   

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
require_once dirname( __FILE__ ) . '/class.jetpack-sync-deflate-codec.php';
3
require_once dirname( __FILE__ ) . '/class.jetpack-sync-queue.php';
4
5
class Jetpack_Sync_Client {
6
	static $default_options_whitelist = array( 'stylesheet', '/^theme_mods_.*$/' );
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $default_options_whitelist.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
7
	static $default_constants_whitelist = array();
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $default_constants_whitelist.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
8
	static $constants_checksum_option_name = 'jetpack_constants_sync_checksum';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $constants_checksum_option_name.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
9
10
	private $sync_queue;
11
	private $codec;
12
	private $options_whitelist;
13
	private $constants_whitelist;
14
	private $meta_types = array( 'post' );
15
16
	// singleton functions
17
	private static $instance;
18
19
	public static function getInstance() {
20
		if ( null === static::$instance ) {
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $instance to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
21
			static::$instance = new static();
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $instance to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
22
		}
23
24
		return static::$instance;
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $instance to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
25
	}
26
27
	// this is necessary because you can't use "new" when you declare instance properties >:(
28
	protected function __construct() {
29
		$this->sync_queue          = new Jetpack_Sync_Queue( 'sync', 100 );
30
		$this->codec               = new Jetpack_Sync_Deflate_Codec();
31
		$this->constants_whitelist = self::$default_constants_whitelist;
32
		$this->options_whitelist   = self::$default_options_whitelist;
33
		$this->init();
34
	}
35
36
	private function init() {
37
		$handler = array( $this, 'action_handler' );
38
39
		// constants
40
		add_action( 'jetpack_sync_current_constants', $handler, 10 );
41
42
		// posts
43
		add_action( 'wp_insert_post', $handler, 10, 3 );
44
		add_action( 'deleted_post', $handler, 10 );
45
46
		// comments
47
		add_action( 'wp_insert_comment', $handler, 10, 2 );
48
		add_action( 'deleted_comment', $handler, 10 );
49
		add_action( 'trashed_comment', $handler, 10 );
50
		add_action( 'spammed_comment', $handler, 10 );
51
52
		// even though it's messy, we implement these hooks because 
53
		// the edit_comment hook doesn't include the data
54
		// so this saves us a DB read for every comment event
55
		foreach ( array( '', 'trackback', 'pingback' ) as $comment_type ) {
56
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
57
				add_action( "comment_{$comment_status}_{$comment_type}", $handler, 10, 2 );
58
			}
59
		}
60
61
		// options
62
		add_action( 'added_option', $handler, 10, 2 );
63
		add_action( 'updated_option', $handler, 10, 3 );
64
		add_action( 'deleted_option', $handler, 10, 1 );
65
66
		// themes
67
		add_action( 'jetpack_sync_current_theme_support', $handler, 10 ); // custom hook, see meta-hooks below
68
69
		// post-meta, and in the future - other meta?
70
		foreach ( $this->meta_types as $meta_type ) {
71
			// we need to make sure we don't commit before we receive these,
72
			// because they're invoked after meta changes are saved to the DB
73
			add_action( "added_{$meta_type}_meta", $handler, 99, 4 );
74
			add_action( "updated_{$meta_type}_meta", $handler, 99, 4 );
75
			add_action( "deleted_{$meta_type}_meta", $handler, 99, 4 );
76
		}
77
78
		/**
79
		 * Other hooks - fire synthetic hooks for all the properties we need to sync,
80
		 * e.g. when a theme changes
81
		 */
82
83
		// themes
84
		add_action( 'switch_theme', array( $this, 'switch_theme_handler' ) );
85
86
		add_action( 'set_site_transient_update_plugins', $handler, 10, 1 );
87
		add_action( 'set_site_transient_update_themes', $handler, 10, 1 );
88
		add_action( 'set_site_transient_update_core', $handler, 10, 1 );
89
90
	}
91
92
	function set_options_whitelist( $options ) {
93
		$this->options_whitelist = $options;
94
	}
95
96
	function set_constants_whitelist( $constants ) {
97
		$this->constants_whitelist = $constants;
98
	}
99
100
	function is_whitelisted_option( $option ) {
101
		foreach ( $this->options_whitelist as $whitelisted_option ) {
102
			if ( $whitelisted_option[0] === '/' && preg_match( $whitelisted_option, $option ) ) {
103
				return true;
104
			} elseif ( $whitelisted_option === $option ) {
105
				return true;
106
			}
107
		}
108
109
		return false;
110
	}
111
112
	function set_codec( iJetpack_Sync_Codec $codec ) {
113
		$this->codec = $codec;
114
	}
115
116
	function set_sync_queue( $queue ) {
117
		$this->sync_queue = $queue;
118
	}
119
120
	function action_handler() {
121
		$current_filter = current_filter();
122
		$args           = func_get_args();
123
124
		if ( $current_filter === 'wp_insert_post' && $args[1]->post_type === 'revision' ) {
125
			return;
126
		}
127
128
		if ( in_array( $current_filter, array( 'deleted_option', 'added_option', 'updated_option' ) )
129
		     &&
130
		     ! $this->is_whitelisted_option( $args[0] )
131
		) {
132
			return;
133
		}
134
		Jetpack_Sync::schedule_sync();
135
		$this->sync_queue->add( array(
136
			$current_filter,
137
			$args
138
		) );
139
	}
140
141
	function switch_theme_handler() {
142
		global $_wp_theme_features;
143
144
		do_action( 'jetpack_sync_current_theme_support', $_wp_theme_features );
145
	}
146
147
	function do_sync() {
148
		$this->maybe_sync_constants();
149
150
		// TODO: only send buffer once, then do the rest in a cron job
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...
151
		$iters = 0;
152
		while ( ( $buffer = $this->sync_queue->checkout() ) && $iters < 100 ) {
153
154
			if ( ! $buffer ) {
155
				// buffer has no items
156
				return;
157
			}
158
159
			if ( is_wp_error( $buffer ) ) {
160
				error_log( "Error fetching buffer: " . $buffer->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<Jetpack_Sync_Queue_Buffer>.

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...
161
162
				return;
163
			}
164
165
			$data = $this->codec->encode( $buffer->get_items() );
166
167
			/**
168
			 * Fires when data is ready to send to the server.
169
			 * Return false or WP_Error to abort the sync (e.g. if there's an error)
170
			 * The items will be automatically re-sent later
171
			 *
172
			 * @since 4.1
173
			 *
174
			 * @param array $data The action buffer
175
			 */
176
			$result = apply_filters( 'jetpack_sync_client_send_data', $data );
177
178
			if ( ! $result || is_wp_error( $result ) ) {
179
				$this->sync_queue->checkin( $buffer );
180
			} else {
181
				$this->sync_queue->close( $buffer );
182
			}
183
			$iters += 1;
184
		}
185
	}
186
187
	private function maybe_sync_constants() {
188
		$constants           = $this->get_all_constants();
189
		$constants_check_sum = $this->get_check_sum( $constants );
190
		if ( $constants_check_sum !== get_option( self::$constants_checksum_option_name ) ) {
191
			do_action( 'jetpack_sync_current_constants', $constants );
192
			update_option( self::$constants_checksum_option_name, $constants_check_sum );
193
		}
194
	}
195
196
	private function get_all_constants() {
197
		return array_combine(
198
			$this->constants_whitelist,
199
			array_map( array( $this, 'get_constant' ), $this->constants_whitelist )
200
		);
201
	}
202
203
	private function get_constant( $constant ) {
204
		if ( defined( $constant ) ) {
205
			return constant( $constant );
206
		}
207
208
		return null;
209
	}
210
211
	private function get_check_sum( $values ) {
212
		return crc32( serialize( $values ) );
213
	}
214
215
	function get_actions() {
216
		// TODO: we should only send a bit at a time, flush_all sends everything
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...
217
		return $this->sync_queue->flush_all();
218
	}
219
220
	function get_all_actions() {
221
		return $this->sync_queue->get_all();
222
	}
223
224
	function reset_state() {
225
		$this->codec               = new Jetpack_Sync_Deflate_Codec();
226
		$this->constants_whitelist = self::$default_constants_whitelist;
227
		$this->options_whitelist   = self::$default_options_whitelist;
228
		delete_option( self::$constants_checksum_option_name );
229
		$this->sync_queue->reset();
230
	}
231
}
232