Completed
Push — issues/1617 ( faec36 )
by Ravinder
20:40
created

Give_Cache::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
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' ) );
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
		return get_option( $cache_key );
102
	}
103
104
	/**
105
	 * Set cache.
106
	 *
107
	 * @since  1.8.7
108
	 *
109
	 * @param  string   $cache_key
110
	 * @param  mixed    $data
111
	 * @param  int|null $expiration Timestamp should be in GMT format.
112
	 *
113
	 * @return mixed
114
	 */
115
116
	public static function set( $cache_key, $data, $expiration = null ) {
117
		if ( ! self::is_valid_cache_key( $cache_key ) ) {
118
			return new WP_Error( 'give_invalid_cache_key', __( 'Cache key format should be give_cache_*', 'give' ) );
119
		}
120
121
		$option_value = array(
122
			'data'       => $data,
123
			'expiration' => ! is_null( $expiration )
124
				? ( $expiration + current_time( 'timestamp', 1 ) )
125
				: null,
126
		);
127
128
		$result = add_option( $cache_key, $option_value, '', 'no' );
129
130
		return $result;
131
	}
132
133
	/**
134
	 * Delete cache.
135
	 *
136
	 * @since  1.8.7
137
	 *
138
	 * @param  string $cache_key
139
	 *
140
	 * @return mixed
141
	 */
142
143
	public static function delete( $cache_key ) {
144
		if ( ! self::is_valid_cache_key( $cache_key ) ) {
145
			return new WP_Error( '', __( 'Cache key format should be give_cache_*', 'give' ) );
146
		}
147
148
		$result = delete_option( $cache_key );
149
150
		return (bool) $result;
151
	}
152
153
	/**
154
	 * Delete all logging cache.
155
	 *
156
	 * @since  1.8.7
157
	 * @access public
158
	 * @global wpdb $wpdb
159
	 *
160
	 * @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...
161
	 */
162
	public static function delete_all() {
163
		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...
164
		$options = $wpdb->get_results(
165
			$wpdb->prepare(
166
				"SELECT option_name, option_value
167
						FROM {$wpdb->options}
168
						Where option_name
169
						LIKE '%%%s%%'",
170
				'give_cache'
171
			),
172
			ARRAY_A
173
		);
174
175
		// Bailout.
176
		if ( empty( $options ) ) {
177
			return false;
178
		}
179
180
		$current_time = current_time( 'timestamp', 1 );
181
182
		// Delete log cache.
183
		foreach ( $options as $option ) {
184
			$option['option_value'] = unserialize( $option['option_value'] );
185
186
			// Do not
187
			if ( is_null( $option['option_value']['expiration'] ) || ( $current_time < $option['option_value']['expiration'] ) ) {
188
				continue;
189
			}
190
191
			self::delete( $option['option_name'] );
192
		}
193
	}
194
195
196
	/**
197
	 * Check cache key validity.
198
	 *
199
	 * @since  1.8.7
200
	 * @access public
201
	 *
202
	 * @param $cache_key
203
	 *
204
	 * @return bool|int
205
	 */
206
	public static function is_valid_cache_key( $cache_key ) {
207
		return ( false !== strpos( $cache_key, 'give_cache_' ) );
208
	}
209
}
210
211
// Initialize
212
Give_Cache::get_instance()->setup_hooks();
213