Completed
Push — issues/1617 ( faec36...85b236 )
by Ravinder
18:05
created

Give_Cache::delete()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 6
nc 7
nop 1
dl 0
loc 11
rs 8.8571
c 0
b 0
f 0
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
	 *
93
	 * @return mixed
94
	 */
95
96
	public static function get( $cache_key ) {
97
		if ( ! self::is_valid_cache_key( $cache_key ) ) {
98
			return new WP_Error( 'give_invalid_cache_key', __( 'Cache key format should be give_cache_*', 'give' ) );
99
		}
100
101
		$option = get_option( $cache_key );
102
103
		// Backward compatibility.
104
		if ( ! is_array( $option ) || empty( $option ) || ! array_key_exists( 'expiration', $option ) ) {
105
			return $option;
106
		}
107
108
		// Get current time.
109
		$current_time = current_time( 'timestamp', 1 );
110
111
		if ( empty( $option['expiration'] ) || ( $current_time < $option['expiration'] ) ) {
112
			$option = $option['data'];
113
		} else {
114
			$option = false;
115
		}
116
		
117
		return $option;
118
	}
119
120
	/**
121
	 * Set cache.
122
	 *
123
	 * @since  1.8.7
124
	 *
125
	 * @param  string   $cache_key
126
	 * @param  mixed    $data
127
	 * @param  int|null $expiration Timestamp should be in GMT format.
128
	 *
129
	 * @return mixed
130
	 */
131
132
	public static function set( $cache_key, $data, $expiration = null ) {
133
		if ( ! self::is_valid_cache_key( $cache_key ) ) {
134
			return new WP_Error( 'give_invalid_cache_key', __( 'Cache key format should be give_cache_*', 'give' ) );
135
		}
136
137
		$option_value = array(
138
			'data'       => $data,
139
			'expiration' => ! is_null( $expiration )
140
				? ( $expiration + current_time( 'timestamp', 1 ) )
141
				: null,
142
		);
143
144
		$result = add_option( $cache_key, $option_value, '', 'no' );
145
146
		return $result;
147
	}
148
149
	/**
150
	 * Delete cache.
151
	 *
152
	 * @since  1.8.7
153
	 *
154
	 * @param  string|array $cache_keys
155
	 */
156
157
	public static function delete( $cache_keys ) {
158
		if( ! empty( $cache_keys ) ) {
159
			$cache_keys = is_array( $cache_keys ) ? $cache_keys : array( $cache_keys );
160
161
			foreach ( $cache_keys as $cache_key ) {
162
				if( self::is_valid_cache_key( $cache_key ) ){
163
					delete_option( $cache_key );
164
				}
165
			}
166
		}
167
	}
168
169
	/**
170
	 * Delete all logging cache.
171
	 *
172
	 * @since  1.8.7
173
	 * @access public
174
	 * @global wpdb $wpdb
175
	 *
176
	 * @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...
177
	 */
178
	public static function delete_all_expired() {
179
		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...
180
		$options = $wpdb->get_results(
181
			$wpdb->prepare(
182
				"SELECT option_name, option_value
183
						FROM {$wpdb->options}
184
						Where option_name
185
						LIKE '%%%s%%'",
186
				'give_cache'
187
			),
188
			ARRAY_A
189
		);
190
191
		// Bailout.
192
		if ( empty( $options ) ) {
193
			return false;
194
		}
195
196
		$current_time = current_time( 'timestamp', 1 );
197
198
		// Delete log cache.
199
		foreach ( $options as $option ) {
200
			$option['option_value'] = maybe_unserialize( $option['option_value'] );
201
202
			if (
203
				! is_array( $option['option_value'] )
204
				|| ! array_key_exists( 'expiration', $option['option_value'] )
205
				|| empty( $option['option_value']['expiration'] )
206
				|| ( $current_time < $option['option_value']['expiration'] )
207
			) {
208
				continue;
209
			}
210
211
			self::delete( $option['option_name'] );
212
		}
213
	}
214
215
216
	/**
217
	 * Check cache key validity.
218
	 *
219
	 * @since  1.8.7
220
	 * @access public
221
	 *
222
	 * @param $cache_key
223
	 *
224
	 * @return bool|int
225
	 */
226
	public static function is_valid_cache_key( $cache_key ) {
227
		return ( false !== strpos( $cache_key, 'give_cache_' ) );
228
	}
229
}
230
231
// Initialize
232
Give_Cache::get_instance()->setup_hooks();
233
234
// @todo implement this with all possible cache
235