Completed
Push — add/sync-rest-2 ( 28e1b3...b696cb )
by
unknown
09:04
created

Jetpack_Sync_Queue::get_checkout_id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
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_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_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
	function reset() {
77
		global $wpdb;
78
		$this->delete_checkout_id();
79
		$wpdb->query( $wpdb->prepare( 
80
			"DELETE FROM $wpdb->options WHERE option_name LIKE %s", "jetpack_sync_queue_{$this->id}-%" 
81
		) );
82
	}
83
84
	function size() {
85
		global $wpdb;
86
		return $wpdb->get_var( $wpdb->prepare( 
87
			"SELECT count(*) FROM $wpdb->options WHERE option_name LIKE %s", "jetpack_sync_queue_{$this->id}-%" 
88
		) );
89
	}
90
91
	function checkout() {
92
		if ( $this->get_checkout_id() ) {
93
			return new WP_Error( 'unclosed_buffer', 'There is an unclosed buffer' );
94
		}
95
96
		$items = $this->fetch_items( $this->checkout_size );
97
		
98
		if ( count( $items ) === 0 ) {
99
			return false;
100
		}
101
102
		$buffer = new Jetpack_Sync_Queue_Buffer( array_slice( $items, 0, $this->checkout_size ) );
103
		
104
		$result = $this->set_checkout_id( $buffer->id );
105
106
		if ( !$result || is_wp_error( $result ) ) {
107
			return $result;
108
		}
109
		
110
		return $buffer;
111
	}
112
113
	function checkin( $buffer ) {
114
		$is_valid = $this->validate_checkout( $buffer );
115
116
		if ( is_wp_error( $is_valid ) ) {
117
			return $is_valid;
118
		}
119
120
		$this->delete_checkout_id();
121
122
		return true;
123
	}
124
125
	function close( $buffer ) {
126
		$is_valid = $this->validate_checkout( $buffer );
127
128
		if ( is_wp_error( $is_valid ) ) {
129
			return $is_valid;
130
		}
131
132
		$this->delete_checkout_id();
133
134
		global $wpdb;
135
136
		// all this fanciness is basically so we can prepare a statement with an IN(id1, id2, id3) clause
137
		$ids_to_remove = $buffer->get_item_ids();
138
		if ( count( $ids_to_remove ) > 0 ) {
139
			$sql = "DELETE FROM $wpdb->options WHERE option_name IN (".implode(', ', array_fill(0, count($ids_to_remove), '%s')).')';
140
			$query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $sql ), $ids_to_remove ) );
141
			$wpdb->query( $query );
142
		}
143
144
		return true;
145
	}
146
147
	function flush_all() {
148
		$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...
149
		$this->reset();
150
		return $items;
151
	}
152
153
	function get_all() {
154
		return $this->fetch_items();
155
	}
156
157
	function set_checkout_size( $new_size ) {
158
		$this->checkout_size = $new_size;
159
	}
160
161
	private function get_checkout_id() {
162
		return get_option( "jetpack_sync_queue_{$this->id}-checkout", false );
163
	}
164
165
	private function set_checkout_id( $checkout_id ) {
166
		$added = add_option( "jetpack_sync_queue_{$this->id}-checkout", $checkout_id, null, true ); // this one we should autoload
167
		if ( ! $added )
168
			return new WP_Error( 'buffer_mismatch', 'Another buffer is already checked out: '.$this->get_checkout_id() );
169
		else
170
			return true;
171
	}
172
173
	private function delete_checkout_id() {
174
		delete_option( "jetpack_sync_queue_{$this->id}-checkout" );
175
	}
176
177
	private function get_option_name() {
178
		// this option is specifically chosen to, as much as possible, preserve time order
179
		// and minimise the possibility of collisions between multiple processes working 
180
		// at the same time
181
		// 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...
182
		// @see: http://php.net/manual/en/function.microtime.php
183
		$timestamp = sprintf( '%.9f', microtime(true) );
184
		return 'jetpack_sync_queue_'.$this->id.'-'.$timestamp.'-'.getmypid();
185
	}
186
187
	private function fetch_items( $limit = null ) {
188
		global $wpdb;
189
190
		if ( $limit ) {
191
			$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 );
192
		} else {
193
			$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}-%" );
194
		}
195
196
		$items = $wpdb->get_results( $query_sql );
197
		foreach( $items as $item ) {
198
			$item->value = maybe_unserialize( $item->value );
199
		} 
200
201
		return $items;
202
	}
203
204
	private function validate_checkout( $buffer ) {
205
		if ( ! $buffer instanceof Jetpack_Sync_Queue_Buffer ) {
206
			return new WP_Error( 'not_a_buffer', 'You must checkin an instance of Jetpack_Sync_Queue_Buffer' );
207
		}
208
209
		$checkout_id = $this->get_checkout_id();
210
211
		if ( !$checkout_id ) {
212
			return new WP_Error( 'buffer_not_checked_out', 'There are no checked out buffers' );
213
		}
214
215
		if ( $checkout_id != $buffer->id ) {
216
			return new WP_Error( 'buffer_mismatch', 'The buffer you checked in was not checked out' );
217
		}
218
219
		return true;
220
	}
221
}