Completed
Push — add/sync-rest-2 ( 600358...909866 )
by
unknown
43:11 queued 33:46
created

Jetpack_Sync_Queue::peek()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
rs 9.4285
cc 2
eloc 5
nc 2
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 array_map( function( $item ) { return $item->value; }, $this->items_with_ids );
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
17
	}
18
19
	public function get_item_ids() {
20
		return array_map( function( $item ) { return $item->id; }, $this->items_with_ids );
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
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
34
	function __construct( $id, $checkout_size = 10 ) {
35
		$this->id = str_replace( '-', '_', $id); // necessary to ensure we don't have ID collisions in the SQL
36
		$this->checkout_size = $checkout_size;
37
	}
38
39
	function add( $item ) {
40
		global $wpdb;
41
		$added = false;
42
		// this basically tries to add the option until enough time has elapsed that
43
		// it has a unique (microtime-based) option key
44
		while(!$added) {
45
			$rows_added = $wpdb->query( $wpdb->prepare( 
46
				"INSERT INTO $wpdb->options (option_name, option_value) VALUES (%s, %s)", 
47
				$this->get_next_data_row_option_name(), 
48
				serialize($item)
49
			) );
50
			$added = ( $rows_added !== 0 );
51
		}
52
	}
53
54
	// Attempts to insert all the items in a single SQL query. May be subject to query size limits!
55
	function add_all( $items ) {
56
		global $wpdb;
57
		$base_option_name = $this->get_next_data_row_option_name();
58
59
		$query = "INSERT INTO $wpdb->options (option_name, option_value) VALUES ";
60
		
61
		$rows = array();
62
63
		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...
64
			$option_name = esc_sql( $base_option_name.'-'.$i );
65
			$option_value = esc_sql( serialize( $items[ $i ] ) );
66
			$rows[] = "('$option_name', '$option_value')";
67
		}
68
69
		$rows_added = $wpdb->query( $query . join( ',', $rows ) );
70
71
		if ( $rows_added !== count( $items ) ) {
72
			return new WP_Error( 'row_count_mismatch', "The number of rows inserted didn't match the size of the input array" );
73
		}
74
	}
75
76
	// Peek at the front-most item on the queue without checking it out
77
	function peek( $count = 1 ) {
78
		$items = $this->fetch_items( $count );
79
		if ( $items ) {
80
			return array_map( function( $item ) { return $item->value; }, $items );
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
81
		} 
82
		return array();
83
	}
84
85
	function reset() {
86
		global $wpdb;
87
		$this->delete_checkout_id();
88
		$wpdb->query( $wpdb->prepare( 
89
			"DELETE FROM $wpdb->options WHERE option_name LIKE %s", "jetpack_sync_queue_{$this->id}-%" 
90
		) );
91
	}
92
93
	function size() {
94
		global $wpdb;
95
		return $wpdb->get_var( $wpdb->prepare( 
96
			"SELECT count(*) FROM $wpdb->options WHERE option_name LIKE %s", "jetpack_sync_queue_{$this->id}-%" 
97
		) );
98
	}
99
100
	function checkout() {
101
		if ( $this->get_checkout_id() ) {
102
			return new WP_Error( 'unclosed_buffer', 'There is an unclosed buffer' );
103
		}
104
105
		$items = $this->fetch_items( $this->checkout_size );
106
		
107
		if ( count( $items ) === 0 ) {
108
			return false;
109
		}
110
111
		$buffer = new Jetpack_Sync_Queue_Buffer( array_slice( $items, 0, $this->checkout_size ) );
112
		
113
		$result = $this->set_checkout_id( $buffer->id );
114
115
		if ( !$result || is_wp_error( $result ) ) {
116
			error_log("badness setting checkout ID (this should not happen)");
117
			return $result;
118
		}
119
		
120
		return $buffer;
121
	}
122
123
	function checkin( $buffer ) {
124
		$is_valid = $this->validate_checkout( $buffer );
125
126
		if ( is_wp_error( $is_valid ) ) {
127
			return $is_valid;
128
		}
129
130
		$this->delete_checkout_id();
131
132
		return true;
133
	}
134
135
	function close( $buffer ) {
136
		$is_valid = $this->validate_checkout( $buffer );
137
138
		if ( is_wp_error( $is_valid ) ) {
139
			return $is_valid;
140
		}
141
142
		$this->delete_checkout_id();
143
144
		global $wpdb;
145
146
		// all this fanciness is basically so we can prepare a statement with an IN(id1, id2, id3) clause
147
		$ids_to_remove = $buffer->get_item_ids();
148
		if ( count( $ids_to_remove ) > 0 ) {
149
			$sql = "DELETE FROM $wpdb->options WHERE option_name IN (".implode(', ', array_fill(0, count($ids_to_remove), '%s')).')';
150
			$query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $sql ), $ids_to_remove ) );
151
			$wpdb->query( $query );
152
		}
153
154
		return true;
155
	}
156
157
	function flush_all() {
158
		$items = array_map( function( $item ) { return $item->value; }, $this->fetch_items() );
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
159
		$this->reset();
160
		return $items;
161
	}
162
163
	function get_all() {
164
		return $this->fetch_items();
165
	}
166
167
	function set_checkout_size( $new_size ) {
168
		$this->checkout_size = $new_size;
169
	}
170
171
	private function get_checkout_id() {
172
		return get_option( $this->get_checkout_option_name(), false );
173
	}
174
175
	private function set_checkout_id( $checkout_id ) {
176
		$added = add_option( $this->get_checkout_option_name(), $checkout_id, null, true ); // this one we should autoload
177
		if ( ! $added )
178
			return new WP_Error( 'buffer_mismatch', 'Another buffer is already checked out: '.$this->get_checkout_id() );
179
		else
180
			return true;
181
	}
182
183
	private function delete_checkout_id() {
184
		delete_option( $this->get_checkout_option_name() );
185
	}
186
187
	private function get_checkout_option_name() {
188
		return "jetpack_sync_queue_{$this->id}-checkout";
189
	}
190
191
	private function get_next_data_row_option_name() {
192
		// this option is specifically chosen to, as much as possible, preserve time order
193
		// and minimise the possibility of collisions between multiple processes working 
194
		// at the same time
195
		// TODO: confirm we only need to support PHP5 (otherwise we'll need to emulate microtime as float)
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...
196
		// @see: http://php.net/manual/en/function.microtime.php
197
		$timestamp = sprintf( '%.9f', microtime(true) );
198
		return 'jetpack_sync_queue_'.$this->id.'-'.$timestamp.'-'.getmypid();
199
	}
200
201
	private function fetch_items( $limit = null ) {
202
		global $wpdb;
203
204
		if ( $limit ) {
205
			$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 );
206
		} else {
207
			$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}-%" );
208
		}
209
210
		$items = $wpdb->get_results( $query_sql );
211
		foreach( $items as $item ) {
212
			$item->value = maybe_unserialize( $item->value );
213
		} 
214
215
		return $items;
216
	}
217
218
	private function validate_checkout( $buffer ) {
219
		if ( ! $buffer instanceof Jetpack_Sync_Queue_Buffer ) {
220
			return new WP_Error( 'not_a_buffer', 'You must checkin an instance of Jetpack_Sync_Queue_Buffer' );
221
		}
222
223
		$checkout_id = $this->get_checkout_id();
224
225
		if ( !$checkout_id ) {
226
			return new WP_Error( 'buffer_not_checked_out', 'There are no checked out buffers' );
227
		}
228
229
		if ( $checkout_id != $buffer->id ) {
230
			return new WP_Error( 'buffer_mismatch', 'The buffer you checked in was not checked out' );
231
		}
232
233
		return true;
234
	}
235
}