Completed
Push — fix/bypass-option-caching-full... ( 643d8f )
by
unknown
08:30
created

Jetpack_Sync_Options   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 32 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 16
loc 50
rs 10
c 0
b 0
f 0
wmc 6
lcom 0
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B write_option() 0 29 3
A read_option() 16 16 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Simple class to read/write to the options table, bypassing 
5
 * problematic caching with get_option/set_option
6
 **/
7
8
class Jetpack_Sync_Options {
9
10
	static function write_option( $name, $value, $autoload = false ) {
11
12
		$autoload_value = $autoload ? 'yes' : 'no';
13
14
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
15
		global $wpdb;
16
		$serialized_value = maybe_serialize( $value );
17
		// try updating, if no update then insert
18
		// TODO: try to deal with the fact that unchanged values can return updated_num = 0
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...
19
		// below we used "insert ignore" to at least suppress the resulting error
20
		$updated_num = $wpdb->query(
21
			$wpdb->prepare(
22
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s", 
23
				$serialized_value,
24
				$name
25
			)
26
		);
27
28
		if ( ! $updated_num ) {
29
			$updated_num = $wpdb->query(
30
				$wpdb->prepare(
31
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, '$autoload_value' )", 
32
					$name,
33
					$serialized_value
34
				)
35
			);
36
		}
37
		return $updated_num;
38
	}
39
40 View Code Duplication
	static function read_option( $name, $default = null ) {
41
		global $wpdb;
42
		$value = $wpdb->get_var( 
43
			$wpdb->prepare(
44
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", 
45
				$name
46
			)
47
		);
48
		$value = maybe_unserialize( $value );
49
50
		if ( $value === null && $default !== null ) {
51
			return $default;
52
		}
53
54
		return $value;
55
	}
56
	
57
}