|
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() { |
|
|
|
|
|
|
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
|
|
|
|
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.