Completed
Push — add/sync-rest-2 ( e8aaa0...ae2fc3 )
by
unknown
35:07 queued 26:11
created

Jetpack_Sync_Utils::get_item_values()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/**
4
 * A buffer of items from the queue that can be checked out
5
 */
6
class Jetpack_Sync_Queue_Buffer {
7
	public $id;
8
	public $items_with_ids;
9
10
	public function __construct( $items_with_ids ) {
11
		$this->id             = uniqid();
12
		$this->items_with_ids = $items_with_ids;
13
	}
14
15
	public function get_items() {
16
		return Jetpack_Sync_Utils::get_item_values( $this->items_with_ids );
17
	}
18
19
	public function get_item_ids() {
20
		return Jetpack_Sync_Utils::get_item_ids( $this->items_with_ids );
21
	}
22
}
23
24
/**
25
 * A persistent queue that can be flushed in increments of N items,
26
 * and which blocks reads until checked-out buffers are checked in or
27
 * closed. This uses raw SQL for two reasons: speed, and not triggering
28
 * tons of added_option callbacks.
29
 */
30
class Jetpack_Sync_Queue {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
31
	public $id;
32
	private $checkout_size;
33
	private $row_iterator;
34
35
	function __construct( $id, $checkout_size = 10 ) {
36
		$this->id            = str_replace( '-', '_', $id ); // necessary to ensure we don't have ID collisions in the SQL
37
		$this->checkout_size = $checkout_size;
38
		$this->row_iterator  = 0;
39
	}
40
41
	function add( $item ) {
42
		global $wpdb;
43
		$added = false;
44
		// this basically tries to add the option until enough time has elapsed that
45
		// it has a unique (microtime-based) option key
46
		while ( ! $added ) {
47
			$rows_added = $wpdb->query( $wpdb->prepare(
48
				"INSERT INTO $wpdb->options (option_name, option_value) VALUES (%s, %s)",
49
				$this->get_next_data_row_option_name(),
50
				serialize( $item )
51
			) );
52
			$added      = ( $rows_added !== 0 );
53
		}
54
	}
55
56
	// Attempts to insert all the items in a single SQL query. May be subject to query size limits!
57
	function add_all( $items ) {
58
		global $wpdb;
59
		$base_option_name = $this->get_next_data_row_option_name();
60
61
		$query = "INSERT INTO $wpdb->options (option_name, option_value) VALUES ";
62
63
		$rows = array();
64
65
		for ( $i = 0; $i < count( $items ); $i += 1 ) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
66
			$option_name  = esc_sql( $base_option_name . '-' . $i );
67
			$option_value = esc_sql( serialize( $items[ $i ] ) );
68
			$rows[]       = "('$option_name', '$option_value')";
69
		}
70
71
		$rows_added = $wpdb->query( $query . join( ',', $rows ) );
72
73
		if ( $rows_added !== count( $items ) ) {
74
			return new WP_Error( 'row_count_mismatch', "The number of rows inserted didn't match the size of the input array" );
75
		}
76
	}
77
78
	// Peek at the front-most item on the queue without checking it out
79
	function peek( $count = 1 ) {
80
		$items = $this->fetch_items( $count );
81
		if ( $items ) {
82
			return Jetpack_Sync_Utils::get_item_values( $items );
83
		}
84
85
		return array();
86
	}
87
88
	function reset() {
89
		global $wpdb;
90
		$this->delete_checkout_id();
91
		$wpdb->query( $wpdb->prepare(
92
			"DELETE FROM $wpdb->options WHERE option_name LIKE %s", "jetpack_sync_queue_{$this->id}-%"
93
		) );
94
	}
95
96
	function size() {
97
		global $wpdb;
98
99
		return $wpdb->get_var( $wpdb->prepare(
100
			"SELECT count(*) FROM $wpdb->options WHERE option_name LIKE %s", "jetpack_sync_queue_{$this->id}-%"
101
		) );
102
	}
103
104
	// we use this peculiar implementation because it's much faster than count(*)
105
	function has_any_items() {
106
		global $wpdb;
107
		$value = $wpdb->get_var( $wpdb->prepare(
108
			"SELECT exists( SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s )", "jetpack_sync_queue_{$this->id}-%"
109
		) );
110
111
		return ( $value === "1" );
112
	}
113
114
	function checkout() {
115
		if ( $this->get_checkout_id() ) {
116
			return new WP_Error( 'unclosed_buffer', 'There is an unclosed buffer' );
117
		}
118
119
		$items = $this->fetch_items( $this->checkout_size );
120
121
		if ( count( $items ) === 0 ) {
122
			return false;
123
		}
124
125
		$buffer = new Jetpack_Sync_Queue_Buffer( array_slice( $items, 0, $this->checkout_size ) );
126
127
		$result = $this->set_checkout_id( $buffer->id );
128
129
		if ( ! $result || is_wp_error( $result ) ) {
130
			error_log( "badness setting checkout ID (this should not happen)" );
131
132
			return $result;
133
		}
134
135
		return $buffer;
136
	}
137
138
	function checkin( $buffer ) {
139
		$is_valid = $this->validate_checkout( $buffer );
140
141
		if ( is_wp_error( $is_valid ) ) {
142
			return $is_valid;
143
		}
144
145
		$this->delete_checkout_id();
146
147
		return true;
148
	}
149
150
	function close( $buffer ) {
151
		$is_valid = $this->validate_checkout( $buffer );
152
153
		if ( is_wp_error( $is_valid ) ) {
154
			return $is_valid;
155
		}
156
157
		$this->delete_checkout_id();
158
159
		global $wpdb;
160
161
		// all this fanciness is basically so we can prepare a statement with an IN(id1, id2, id3) clause
162
		$ids_to_remove = $buffer->get_item_ids();
163
		if ( count( $ids_to_remove ) > 0 ) {
164
			$sql   = "DELETE FROM $wpdb->options WHERE option_name IN (" . implode( ', ', array_fill( 0, count( $ids_to_remove ), '%s' ) ) . ')';
165
			$query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $sql ), $ids_to_remove ) );
166
			$wpdb->query( $query );
167
		}
168
169
		return true;
170
	}
171
172
	function flush_all() {
173
		$items = Jetpack_Sync_Utils::get_item_values( $this->fetch_items() );
174
		$this->reset();
175
176
		return $items;
177
	}
178
179
	function get_all() {
180
		return $this->fetch_items();
181
	}
182
183
	function set_checkout_size( $new_size ) {
184
		$this->checkout_size = $new_size;
185
	}
186
187
	private function get_checkout_id() {
188
		return get_option( $this->get_checkout_option_name(), false );
189
	}
190
191
	private function set_checkout_id( $checkout_id ) {
192
		$added = add_option( $this->get_checkout_option_name(), $checkout_id, null, true ); // this one we should autoload
193
		if ( ! $added ) {
194
			return new WP_Error( 'buffer_mismatch', 'Another buffer is already checked out: ' . $this->get_checkout_id() );
195
		} else {
196
			return true;
197
		}
198
	}
199
200
	private function delete_checkout_id() {
201
		delete_option( $this->get_checkout_option_name() );
202
	}
203
204
	private function get_checkout_option_name() {
205
		return "jetpack_sync_queue_{$this->id}-checkout";
206
	}
207
208
	private function get_next_data_row_option_name() {
209
		// this option is specifically chosen to, as much as possible, preserve time order
210
		// and minimise the possibility of collisions between multiple processes working 
211
		// at the same time
212
		// TODO: confirm we only need to support PHP 5.05+ (otherwise we'll need to emulate microtime as float, and avoid PHP_INT_MAX)
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...
213
		// @see: http://php.net/manual/en/function.microtime.php
214
		$timestamp = sprintf( '%.6f', microtime( true ) );
215
216
		// row iterator is used to avoid collisions where we're writing data waaay fast in a single process
217
		if ( $this->row_iterator === PHP_INT_MAX ) {
218
			$this->row_iterator = 0;
219
		} else {
220
			$this->row_iterator += 1;
221
		}
222
223
		return 'jetpack_sync_queue_' . $this->id . '-' . $timestamp . '-' . getmypid() . '-' . $this->row_iterator;
224
	}
225
226
	private function fetch_items( $limit = null ) {
227
		global $wpdb;
228
229
		if ( $limit ) {
230
			$query_sql = $wpdb->prepare( "SELECT option_name AS id, option_value AS value FROM $wpdb->options WHERE option_name LIKE %s ORDER BY option_name ASC LIMIT %d", "jetpack_sync_queue_{$this->id}-%", $limit );
231
		} else {
232
			$query_sql = $wpdb->prepare( "SELECT option_name AS id, option_value AS value FROM $wpdb->options WHERE option_name LIKE %s ORDER BY option_name ASC", "jetpack_sync_queue_{$this->id}-%" );
233
		}
234
235
		$items = $wpdb->get_results( $query_sql );
236
		foreach ( $items as $item ) {
237
			$item->value = maybe_unserialize( $item->value );
238
		}
239
240
		return $items;
241
	}
242
243
	private function validate_checkout( $buffer ) {
244
		if ( ! $buffer instanceof Jetpack_Sync_Queue_Buffer ) {
245
			return new WP_Error( 'not_a_buffer', 'You must checkin an instance of Jetpack_Sync_Queue_Buffer' );
246
		}
247
248
		$checkout_id = $this->get_checkout_id();
249
250
		if ( ! $checkout_id ) {
251
			return new WP_Error( 'buffer_not_checked_out', 'There are no checked out buffers' );
252
		}
253
254
		if ( $checkout_id != $buffer->id ) {
255
			return new WP_Error( 'buffer_mismatch', 'The buffer you checked in was not checked out' );
256
		}
257
258
		return true;
259
	}
260
}
261
262
class Jetpack_Sync_Utils {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
263
264
	static function get_item_values( $items ) {
265
		return array_map( array( __CLASS__, 'get_item_value' ), $items );
266
	}
267
268
	static function get_item_ids( $items ) {
269
		return array_map( array( __CLASS__, 'get_item_id' ), $items );
270
	}
271
272
	static private function get_item_value( $item ) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
273
		return $item->value;
274
	}
275
276
	static private function get_item_id( $item ) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
277
		return $item->id;
278
	}
279
}
280