Completed
Push — issues/1617 ( 52489e...cfb01a )
by Ravinder
19:52
created

Give_Cache   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 300
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 300
rs 8.2608
c 0
b 0
f 0
wmc 40
lcom 2
cbo 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A get_instance() 0 7 2
A setup_hooks() 0 4 1
A get_key() 0 10 2
C get() 0 29 8
A set() 0 20 4
B delete() 0 27 6
C delete_all_expired() 0 37 8
C get_options_like() 0 42 7
A is_valid_cache_key() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Give_Cache often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Give_Cache, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 17 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

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

Loading history...
2
/**
3
 * Class for managing cache
4
 *
5
 * @package     Give
6
 * @subpackage  Classes/Give_Cache
7
 * @copyright   Copyright (c) 2017, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.8.7
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
class Give_Cache {
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
18
	/**
19
	 * Instance.
20
	 *
21
	 * @since  1.8.7
22
	 * @access static
23
	 * @var
24
	 */
25
	static private $instance;
26
27
	/**
28
	 * Singleton pattern.
29
	 *
30
	 * @since  1.8.7
31
	 * @access private
32
	 * Give_Cache constructor.
33
	 */
34
	private function __construct() {
35
	}
36
37
38
	/**
39
	 * Get instance.
40
	 *
41
	 * @since  1.8.7
42
	 * @access public
43
	 * @return static
44
	 */
45
	public static function get_instance() {
46
		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...
47
			self::$instance = new static();
48
		}
49
50
		return self::$instance;
51
	}
52
53
	/**
54
	 * Setup hooks.
55
	 *
56
	 * @since  1.8.7
57
	 * @access public
58
	 */
59
	public function setup_hooks() {
60
		// weekly delete all expired cache.
61
		add_action( 'give_weekly_scheduled_events', array( $this, 'delete_all_expired' ) );
62
	}
63
64
	/**
65
	 * Get cache key.
66
	 *
67
	 * @since  1.8.7
68
	 *
69
	 * @param  string $action     Cache key prefix.
70
	 * @param  array  $query_args Query array.
71
	 *
72
	 * @return string
73
	 */
74
75
	public static function get_key( $action, $query_args ) {
76
		$cache_key = "give_cache_{$action}";
77
78
		// Bailout.
79
		if ( ! empty( $query_args ) ) {
80
			$cache_key = "{$cache_key}_" . substr( md5( serialize( $query_args ) ), 0, 15 );
81
		}
82
83
		return $cache_key;
84
	}
85
86
	/**
87
	 * Get cache.
88
	 *
89
	 * @since  1.8.7
90
	 *
91
	 * @param  string $cache_key
92
	 * @param  bool   $custom_key
93
	 * @param  mixed  $query_args
94
	 *
95
	 * @return mixed
96
	 */
97
98
	public static function get( $cache_key, $custom_key = false, $query_args = array() ) {
99
		if ( ! self::is_valid_cache_key( $cache_key ) ) {
100
			if ( ! $custom_key ) {
101
				return new WP_Error( 'give_invalid_cache_key', __( 'Cache key format should be give_cache_*', 'give' ) );
102
			}
103
104
			$cache_key = self::get_key( $cache_key, $query_args );
105
		}
106
107
		$option = get_option( $cache_key );
108
109
		// Backward compatibility (<1.8.7).
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
		if ( ! is_array( $option ) || empty( $option ) || ! array_key_exists( 'expiration', $option ) ) {
111
			return $option;
112
		}
113
114
		error_log( print_r( $option, true ) . "\n", 3, WP_CONTENT_DIR . '/debug_new.log' );
115
116
		// Get current time.
117
		$current_time = current_time( 'timestamp', 1 );
118
119
		if ( empty( $option['expiration'] ) || ( $current_time < $option['expiration'] ) ) {
120
			$option = $option['data'];
121
		} else {
122
			$option = false;
123
		}
124
125
		return $option;
126
	}
127
128
	/**
129
	 * Set cache.
130
	 *
131
	 * @since  1.8.7
132
	 *
133
	 * @param  string   $cache_key
134
	 * @param  mixed    $data
135
	 * @param  int|null $expiration Timestamp should be in GMT format.
136
	 * @param  bool     $custom_key
137
	 * @param  mixed    $query_args
138
	 *
139
	 * @return mixed
140
	 */
141
142
	public static function set( $cache_key, $data, $expiration = null, $custom_key = false, $query_args = array() ) {
143
		if ( ! self::is_valid_cache_key( $cache_key ) ) {
144
			if ( ! $custom_key ) {
145
				return new WP_Error( 'give_invalid_cache_key', __( 'Cache key format should be give_cache_*', 'give' ) );
146
			}
147
148
			$cache_key = self::get_key( $cache_key, $query_args );
149
		}
150
151
		$option_value = array(
152
			'data'       => $data,
153
			'expiration' => ! is_null( $expiration )
154
				? ( $expiration + current_time( 'timestamp', 1 ) )
155
				: null,
156
		);
157
158
		$result = add_option( $cache_key, $option_value, '', 'no' );
159
160
		return $result;
161
	}
162
163
	/**
164
	 * Delete cache.
165
	 *
166
	 * @since  1.8.7
167
	 *
168
	 * @param  string|array $cache_keys
169
	 *
170
	 * @return bool|WP_Error
171
	 */
172
173
	public static function delete( $cache_keys ) {
174
		$result = true;
175
		$invalid_keys = array();
176
177
		if ( ! empty( $cache_keys ) ) {
178
			$cache_keys = is_array( $cache_keys ) ? $cache_keys : array( $cache_keys );
179
180
			foreach ( $cache_keys as $cache_key ) {
181
				if ( ! self::is_valid_cache_key( $cache_key ) ) {
182
					$invalid_keys[] = $cache_key;
183
					$result = false;
184
				}
185
186
				delete_option( $cache_key );
187
			}
188
		}
189
190
		if( ! $result ) {
191
			$result = new WP_Error(
192
				'give_invalid_cache_key',
193
					__( 'Cache key format should be give_cache_*', 'give' ),
194
					$invalid_keys
195
			);
196
		}
197
198
		return $result;
199
	}
200
201
	/**
202
	 * Delete all logging cache.
203
	 *
204
	 * @since  1.8.7
205
	 * @access public
206
	 * @global wpdb $wpdb
207
	 *
208
	 * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
209
	 */
210
	public static function delete_all_expired() {
211
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
212
		$options = $wpdb->get_results(
213
			$wpdb->prepare(
214
				"SELECT option_name, option_value
215
						FROM {$wpdb->options}
216
						Where option_name
217
						LIKE '%%%s%%'",
218
				'give_cache'
219
			),
220
			ARRAY_A
221
		);
222
223
		// Bailout.
224
		if ( empty( $options ) ) {
225
			return false;
226
		}
227
228
		$current_time = current_time( 'timestamp', 1 );
229
230
		// Delete log cache.
231
		foreach ( $options as $option ) {
232
			$option['option_value'] = maybe_unserialize( $option['option_value'] );
233
234
			if (
235
				! self::is_valid_cache_key( $option['option_name'] )
236
				|| ! is_array( $option['option_value'] ) // Backward compatibility (<1.8.7).
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
237
				|| ! array_key_exists( 'expiration', $option['option_value'] ) // Backward compatibility (<1.8.7).
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
238
				|| empty( $option['option_value']['expiration'] )
239
				|| ( $current_time < $option['option_value']['expiration'] )
240
			) {
241
				continue;
242
			}
243
244
			self::delete( $option['option_name'] );
245
		}
246
	}
247
248
249
	/**
250
	 * Get list of options like.
251
	 *
252
	 * @since  1.8.7
253
	 * @access public
254
	 *
255
	 * @param string $option_name
256
	 * @param bool   $fields
257
	 *
258
	 * @return array
259
	 */
260
	public static function get_options_like( $option_name, $fields = false ) {
261
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
262
263
		if ( empty( $option_name ) ) {
264
			return array();
265
		}
266
267
		$field_names = $fields ? 'option_name, option_value' : 'option_name';
268
269
		if ( $fields ) {
270
			$options = $wpdb->get_results(
271
				$wpdb->prepare(
272
					"SELECT {$field_names }
273
						FROM {$wpdb->options}
274
						Where option_name
275
						LIKE '%%%s%%'",
276
					"give_cache_{$option_name}"
277
				),
278
				ARRAY_A
279
			);
280
		} else {
281
			$options = $wpdb->get_col(
282
				$wpdb->prepare(
283
					"SELECT *
284
						FROM {$wpdb->options}
285
						Where option_name
286
						LIKE '%%%s%%'",
287
					"give_cache_{$option_name}"
288
				),
289
				1
290
			);
291
		}
292
293
		if ( ! empty( $options ) && $fields ) {
294
			foreach ( $options as $index => $option ) {
295
				$option['option_value'] = maybe_unserialize( $option['option_value'] );
296
				$options[ $index ]      = $option;
297
			}
298
		}
299
300
		return $options;
301
	}
302
303
	/**
304
	 * Check cache key validity.
305
	 *
306
	 * @since  1.8.7
307
	 * @access public
308
	 *
309
	 * @param $cache_key
310
	 *
311
	 * @return bool|int
312
	 */
313
	public static function is_valid_cache_key( $cache_key ) {
314
		return ( false !== strpos( $cache_key, 'give_cache_' ) );
315
	}
316
}
317
318
// Initialize
319
Give_Cache::get_instance()->setup_hooks();
320
321
// @todo implement this with all possible cache
322