Completed
Push — master ( 9f3eac...f0c1b5 )
by David
02:49 queued 13s
created

Task_Ajax_Adapter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 59
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A start() 0 26 3
A get_task() 0 4 1
1
<?php
2
/**
3
 * This file is part of the `task` subfolder and provides an ajax adapter class to publish tasks
4
 * as ajax end-points.
5
 *
6
 * @since 1.0.0
7
 * @package Wordlift_Framework\Tasks
8
 */
9
10
namespace Wordlift\Tasks;
11
12
/**
13
 * Define the Task_Ajax_Adapter class.
14
 *
15
 * @since 1.0.0
16
 */
17
class Task_Ajax_Adapter {
18
19
	/**
20
	 * @var Task
21
	 */
22
	private $task;
23
24
	private $action_name;
25
26
	/**
27
	 * Task_Ajax_Adapter constructor.
28
	 *
29
	 * @param Task $task
30
	 */
31
	public function __construct( $task ) {
32
33
		$this->task = $task;
34
35
		$this->action_name = $task->get_id();
36
		add_action( 'wp_ajax_' . $this->action_name, array( $this, 'start' ) );
37
38
	}
39
40
	function start() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
41
42
		// First check if there is a valid nonce.
43
		check_ajax_referer( $this->action_name );
44
45
		// Get the offset.
46
		$offset = filter_input( INPUT_POST, 'offset', FILTER_SANITIZE_NUMBER_INT ) ?: 0;
47
48
		// Compatibility fix for FacetWP, which somewhere in some filter checks for the $_POST array.
49
		unset( $_POST['offset'] );
50
51
		// Create an AJAX progress. The AJAX progress returns the progress data to the AJAX client, which
52
		// in turn calls the next batch.
53
		$ajax_progress = new Task_Ajax_Progress( $this->action_name );
54
55
		// Finally create the task runner and start it.
56
		$task_runner = new Task_Single_Instance_Task_Runner( $this->task, true, array( $ajax_progress ) );
57
58
		try {
59
			// Start the task runner, 1 item at a time.
60
			$task_runner->start( 1, $offset );
61
		} catch ( Task_Another_Instance_Is_Running_Exception $e ) {
62
			wp_send_json_error( "A task is already running." );
63
		}
64
65
	}
66
67
	/**
68
	 * @return Task
69
	 */
70
	public function get_task() {
71
72
		return $this->task;
73
	}
74
75
}
76