Test Failed
Push — feature/upgrdae-auto-pause ( 76a297 )
by Ravinder
06:26
created

Give_Background_Updater   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 289
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 289
rs 8.8
c 0
b 0
f 0
wmc 36
lcom 1
cbo 2

11 Methods

Rating   Name   Duplication   Size   Complexity  
A dispatch() 0 4 1
A get_all_batch() 0 3 1
A handle_cron_healthcheck() 0 15 4
A schedule_event() 0 5 3
D task() 0 102 13
A complete() 0 19 3
A get_memory_limit() 0 15 4
A maybe_handle() 0 20 4
A is_paused_process() 0 8 1
A get_identifier() 0 3 1
A get_cron_identifier() 0 3 1
1
<?php
2
/**
3
 * Background Updater
4
 *
5
 * Uses https://github.com/A5hleyRich/wp-background-processing to handle DB
6
 * updates in the background.
7
 *
8
 * @class    Give_Background_Updater
9
 * @version  2.0.0
10
 * @package  Give/Classes
11
 * @category Class
12
 * @author   WordImpress
13
 */
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * Give_Background_Updater Class.
20
 */
21
class Give_Background_Updater extends WP_Background_Process {
22
23
	/**
24
	 * @var string
25
	 */
26
	protected $action = 'give_db_updater';
27
28
	/**
29
	 * Dispatch updater.
30
	 *
31
	 * Updater will still run via cron job if this fails for any reason.
32
	 */
33
	public function dispatch() {
34
		/* @var WP_Background_Process $dispatched */
35
		parent::dispatch();
36
	}
37
38
39
	/**
40
	 * Get all batches.
41
	 *
42
	 * @since  2.0
43
	 * @access public
44
	 * @return stdClass
45
	 */
46
	public function get_all_batch() {
47
		return parent::get_batch();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (get_batch() instead of get_all_batch()). Are you sure this is correct? If so, you might want to change this to $this->get_batch().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
48
	}
49
50
	/**
51
	 * Handle cron healthcheck
52
	 *
53
	 * Restart the background process if not already running
54
	 * and data exists in the queue.
55
	 */
56
	public function handle_cron_healthcheck() {
57
		if ( $this->is_process_running() || $this->is_paused_process()  ) {
58
			// Background process already running.
59
			return;
60
		}
61
62
		if ( $this->is_queue_empty() ) {
63
			// No data to process.
64
			$this->clear_scheduled_event();
65
66
			return;
67
		}
68
69
		$this->handle();
70
	}
71
72
	/**
73
	 * Schedule fallback event.
74
	 */
75
	protected function schedule_event() {
76
		if ( ! wp_next_scheduled( $this->cron_hook_identifier ) && ! $this->is_paused_process() ) {
77
			wp_schedule_event( time() + 10, $this->cron_interval_identifier, $this->cron_hook_identifier );
78
		}
79
	}
80
81
	/**
82
	 * Task
83
	 *
84
	 * Override this method to perform any actions required on each
85
	 * queue item. Return the modified item for further processing
86
	 * in the next pass through. Or, return false to remove the
87
	 * item from the queue.
88
	 *
89
	 * @param array $update Update info
90
	 *
91
	 * @return mixed
92
	 */
93
	protected function task( $update ) {
94
		// Pause upgrade immediately if admin pausing upgrades.
95
		if( $this->is_paused_process() ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
96
			wp_die();
97
		}
98
99
		if ( empty( $update ) ) {
100
			return false;
101
		}
102
103
		/* @var  Give_Updates $give_updates */
104
		$give_updates  = Give_Updates::get_instance();
105
		$resume_update = get_option(
106
			'give_doing_upgrade',
107
0 ignored issues
show
Coding Style introduced by
There should be no empty lines in a multi-line function call.
Loading history...
108
			// Default update.
109
			array(
110
				'update_info'      => $update,
111
				'step'             => 1,
112
				'update'           => 1,
113
				'heading'          => sprintf( 'Update %s of {update_count}', 1 ),
114
				'percentage'       => $give_updates->percentage,
115
				'total_percentage' => 0,
116
			)
117
		);
118
119
		// Continuously skip update if previous update does not complete yet.
120
		if (
121
			$resume_update['update_info']['id'] !== $update['id'] &&
122
			! give_has_upgrade_completed( $resume_update['update_info']['id'] )
123
		) {
124
			return $update;
125
		}
126
127
		// Set params.
128
		$resume_update['update_info'] = $update;
129
		$give_updates->step           = absint( $resume_update['step'] );
130
		$give_updates->update         = absint( $resume_update['update'] );
131
		$is_parent_update_completed   = $give_updates->is_parent_updates_completed( $update );
132
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
133
134
		// Skip update if dependency update does not complete yet.
135
		if ( empty( $is_parent_update_completed ) ) {
136
			// @todo: set error when you have only one update with invalid dependency
137
			if ( ! is_null( $is_parent_update_completed ) ) {
138
				return $update;
139
			}
140
141
			return false;
142
		}
143
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
144
145
		// Pause upgrade immediately if found following:
146
		// 1. Running update number greater then total update count
147
		// 2. Processing percentage greater then 100%
148
		if( (
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
149
			101 < $resume_update['total_percentage'] ) ||
150
		    ( $give_updates->get_total_db_update_count() < $resume_update['update'] ) ||
151
		    ! in_array( $resume_update['update_info']['id'], $give_updates->get_update_ids() )
152
		) {
153
			if( ! $this->is_paused_process() ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
154
				$give_updates->__pause_db_update(true);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
155
			}
156
157
			update_option( 'give_upgrade_error', 1 );
158
159
			wp_die();
160
		}
161
162
		// Disable cache.
163
		Give_Cache::disable();
164
165
		// Run update.
166
		if ( is_array( $update['callback'] ) ) {
167
			$update['callback'][0]->$update['callback'][1]();
168
		} else {
169
			$update['callback']();
170
		}
171
172
		// Set update info.
173
		$doing_upgrade_args = array(
174
			'update_info'      => $update,
175
			'step'             => ++ $give_updates->step,
176
			'update'           => $give_updates->update,
177
			'heading'          => sprintf( 'Update %s of %s', $give_updates->update, get_option( 'give_db_update_count' ) ),
178
			'percentage'       => $give_updates->percentage,
179
			'total_percentage' => $give_updates->get_db_update_processing_percentage(),
180
		);
181
182
		// Cache upgrade.
183
		update_option( 'give_doing_upgrade', $doing_upgrade_args );
184
185
		// Enable cache.
186
		Give_Cache::enable();
187
188
		// Check if current update completed or not.
189
		if ( give_has_upgrade_completed( $update['id'] ) ) {
190
			return false;
191
		}
192
193
		return $update;
194
	}
195
196
	/**
197
	 * Complete
198
	 *
199
	 * Override if applicable, but ensure that the below actions are
200
	 * performed, or, call parent::complete().
201
	 */
202
	protected function complete() {
203
		if ( $this->is_paused_process() ) {
204
			return false;
205
		}
206
207
		parent::complete();
208
209
		delete_option( 'give_upgrade_error' );
210
		delete_option( 'give_db_update_count' );
211
		delete_option( 'give_doing_upgrade' );
212
		add_option( 'give_show_db_upgrade_complete_notice', 1, '', 'no' );
213
214
		// Flush cache.
215
		Give_Cache::get_instance()->flush_cache();
216
217
		if ( $cache_keys = Give_Cache::get_options_like( '' ) ) {
218
			Give_Cache::delete( $cache_keys );
219
		}
220
	}
221
222
	/**
223
	 * Get memory limit
224
	 *
225
	 * @return int
226
	 */
227
	protected function get_memory_limit() {
228
		if ( function_exists( 'ini_get' ) ) {
229
			$memory_limit = ini_get( 'memory_limit' );
230
		} else {
231
			// Sensible default.
232
			$memory_limit = '128M';
233
		}
234
235
		if ( ! $memory_limit || '-1' === $memory_limit ) {
236
			// Unlimited, set to 32GB.
237
			$memory_limit = '32000M';
238
		}
239
240
		return intval( $memory_limit ) * 1024 * 1024;
241
	}
242
243
	/**
244
	 * Maybe process queue
245
	 *
246
	 * Checks whether data exists within the queue and that
247
	 * the process is not already running.
248
	 */
249
	public function maybe_handle() {
250
		// Don't lock up other requests while processing
251
		session_write_close();
0 ignored issues
show
introduced by
The use of PHP session function session_write_close() is prohibited.
Loading history...
252
253
		if ( $this->is_process_running() || $this->is_paused_process() ) {
254
			// Background process already running.
255
			wp_die();
256
		}
257
258
		if ( $this->is_queue_empty() ) {
259
			// No data to process.
260
			wp_die();
261
		}
262
263
		check_ajax_referer( $this->identifier, 'nonce' );
264
265
		$this->handle();
266
267
		wp_die();
268
	}
269
270
271
	/**
272
	 * Check if backgound upgrade paused or not.
273
	 *
274
	 * @since 2.0
275
	 * @access public
276
	 * @return bool
277
	 */
278
	public function is_paused_process(){
279
		// Not using get_option because i am facing some caching releated issue.
280
		global $wpdb;
281
282
		$options = $wpdb->get_results( "SELECT * FROM $wpdb->options WHERE option_name='give_paused_batches' LIMIT 1" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
283
284
		return ! empty( $options );
285
	}
286
287
288
	/**
289
	 * Get identifier
290
	 *
291
	 * @since  2.0
292
	 * @access public
293
	 * @return mixed|string
294
	 */
295
	public function get_identifier() {
296
		return $this->identifier;
297
	}
298
299
	/**
300
	 * Get cron identifier
301
	 *
302
	 * @since  2.0
303
	 * @access public
304
	 * @return mixed|string
305
	 */
306
	public function get_cron_identifier() {
307
		return $this->cron_hook_identifier;
308
	}
309
}
310