Passed
Pull Request — master (#195)
by Jonathan
02:48
created

Object_Sync_Sf_Queue   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 236
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 57
c 3
b 1
f 0
dl 0
loc 236
rs 10
wmc 21

13 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 2 1
A schedule_cron() 0 2 1
A action_scheduler_concurrent_batches() 0 2 1
A search() 0 2 1
A get_next() 0 9 2
A action_scheduler_batch_size() 0 2 1
A get_frequency() 0 25 4
A schedule_single() 0 2 1
A cancel() 0 2 1
A schedule_recurring() 0 2 1
A get_frequencies() 0 24 5
A add_actions() 0 3 1
A __construct() 0 7 1
1
<?php
2
/**
3
 * Object Sync for Salesforce Queue
4
 */
5
6
if ( ! defined( 'ABSPATH' ) ) {
7
	exit; // Exit if accessed directly.
8
}
9
10
/**
11
 * Object_Sync_Sf_Queue
12
 *
13
 * Manage the queue
14
 *
15
 */
16
class Object_Sync_Sf_Queue {
17
18
	protected $wpdb;
19
	protected $version;
20
	protected $slug;
21
	protected $schedulable_classes;
22
23
	public function __construct( $wpdb, $version, $slug, $schedulable_classes ) {
24
		$this->wpdb                = $wpdb;
25
		$this->version             = $version;
26
		$this->slug                = $slug;
27
		$this->schedulable_classes = $schedulable_classes;
28
29
		$this->add_actions();
30
	}
31
32
	/**
33
	 * Add actions
34
	 *
35
	 */
36
	private function add_actions() {
37
		add_filter( 'action_scheduler_queue_runner_batch_size', array( $this, 'action_scheduler_batch_size' ) );
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
		/** @scrutinizer ignore-call */ 
38
  add_filter( 'action_scheduler_queue_runner_batch_size', array( $this, 'action_scheduler_batch_size' ) );
Loading history...
38
		add_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'action_scheduler_concurrent_batches' ) );
39
	}
40
41
	/**
42
	 * Set the batch size. Todo: we should maybe make this a configurable option.
43
	 *
44
	 * @param int  $batch_size
45
	 * @return int  $batch_size
46
	 */
47
	public function action_scheduler_batch_size( $batch_size ) {
0 ignored issues
show
Unused Code introduced by
The parameter $batch_size is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

47
	public function action_scheduler_batch_size( /** @scrutinizer ignore-unused */ $batch_size ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
48
		return 10;
49
	}
50
51
	/**
52
	 * Set the number of concurrent batches that can run. Todo: we should maybe make this a configurable option.
53
	 *
54
	 * @param int  $concurrent_batches
55
	 * @return int  $concurrent_batches
56
	 */
57
	public function action_scheduler_concurrent_batches( $concurrent_batches ) {
0 ignored issues
show
Unused Code introduced by
The parameter $concurrent_batches is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

57
	public function action_scheduler_concurrent_batches( /** @scrutinizer ignore-unused */ $concurrent_batches ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
58
		return 5;
59
	}
60
61
	/**
62
	 * Get all the schedules with their frequencies, sorted
63
	 *
64
	 * @param string  $unit The unit of time
65
	 * @param string  $sort Which direction to sort
66
	 * @return array $this->schedulable_classes
67
	 */
68
	public function get_frequencies( $unit = 'seconds', $sort = 'asc' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $unit is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

68
	public function get_frequencies( /** @scrutinizer ignore-unused */ $unit = 'seconds', $sort = 'asc' ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
69
70
		foreach ( $this->schedulable_classes as $key => $schedule ) {
71
			$this->schedulable_classes[ $key ]['frequency'] = $this->get_frequency( $key, 'seconds' );
72
		}
73
74
		if ( 'asc' === $sort ) {
75
			uasort( $this->schedulable_classes, function( $a, $b ) {
76
				// we want zero values at the top of an ascending sort
77
				if ( 0 === $a ) {
78
					return 1;
79
				}
80
				if ( 0 === $b ) {
81
					return -1;
82
				}
83
				return $a['frequency'] - $b['frequency'];
84
			});
85
		} else {
86
			uasort( $this->schedulable_classes, function( $a, $b ) {
87
				return $b['frequency'] - $a['frequency'];
88
			});
89
		}
90
91
		return $this->schedulable_classes;
92
93
	}
94
95
	/**
96
	 * Get a single schedule item's frequency
97
	 *
98
	 * @param string $name The name of the schedule
99
	 * @param string  $unit The unit of time
100
	 * @return int How often it runs in that unit of time
101
	 */
102
	public function get_frequency( $name, $unit ) {
103
		$schedule_number = filter_var( get_option( 'object_sync_for_salesforce_' . $name . '_schedule_number', '' ), FILTER_VALIDATE_INT );
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

103
		$schedule_number = filter_var( /** @scrutinizer ignore-call */ get_option( 'object_sync_for_salesforce_' . $name . '_schedule_number', '' ), FILTER_VALIDATE_INT );
Loading history...
104
		$schedule_unit   = get_option( 'object_sync_for_salesforce_' . $name . '_schedule_unit', '' );
105
106
		switch ( $schedule_unit ) {
107
			case 'minutes':
108
				$seconds = 60;
109
				$minutes = 1;
110
				break;
111
			case 'hours':
112
				$seconds = 3600;
113
				$minutes = 60;
114
				break;
115
			case 'days':
116
				$seconds = 86400;
117
				$minutes = 1440;
118
				break;
119
			default:
120
				$seconds = 0;
121
				$minutes = 0;
122
		}
123
124
		$total = ${$unit} * $schedule_number;
125
126
		return $total;
127
	}
128
129
	/**
130
	 * Enqueue an action to run one time, as soon as possible
131
	 *
132
	 * @param string $hook The hook to trigger.
133
	 * @param array  $args Arguments to pass when the hook triggers.
134
	 * @param string $group The group to assign this job to.
135
	 * @return string The action ID.
136
	 */
137
	public function add( $hook, $args = array(), $group = '' ) {
138
		return $this->schedule_single( time(), $hook, $args, $group );
139
	}
140
141
	/**
142
	 * Schedule an action to run once at some time in the future
143
	 *
144
	 * @param int    $timestamp When the job will run.
145
	 * @param string $hook The hook to trigger.
146
	 * @param array  $args Arguments to pass when the hook triggers.
147
	 * @param string $group The group to assign this job to.
148
	 * @return string The action ID.
149
	 */
150
	public function schedule_single( $timestamp, $hook, $args = array(), $group = '' ) {
151
		return as_schedule_single_action( $timestamp, $hook, $args, $group );
152
	}
153
154
	/**
155
	 * Schedule a recurring action
156
	 *
157
	 * @param int    $timestamp When the first instance of the job will run.
158
	 * @param int    $interval_in_seconds How long to wait between runs.
159
	 * @param string $hook The hook to trigger.
160
	 * @param array  $args Arguments to pass when the hook triggers.
161
	 * @param string $group The group to assign this job to.
162
	 * @return string The action ID.
163
	 */
164
	public function schedule_recurring( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '' ) {
165
		return as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group );
166
	}
167
168
	/**
169
	 * Schedule an action that recurs on a cron-like schedule.
170
	 *
171
	 * @param int    $timestamp The schedule will start on or after this time.
172
	 * @param string $cron_schedule A cron-link schedule string.
173
	 * @see http://en.wikipedia.org/wiki/Cron
174
	 *   *    *    *    *    *    *
175
	 *   ┬    ┬    ┬    ┬    ┬    ┬
176
	 *   |    |    |    |    |    |
177
	 *   |    |    |    |    |    + year [optional]
178
	 *   |    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
179
	 *   |    |    |    +---------- month (1 - 12)
180
	 *   |    |    +--------------- day of month (1 - 31)
181
	 *   |    +-------------------- hour (0 - 23)
182
	 *   +------------------------- min (0 - 59)
183
	 * @param string $hook The hook to trigger.
184
	 * @param array  $args Arguments to pass when the hook triggers.
185
	 * @param string $group The group to assign this job to.
186
	 * @return string The action ID
187
	 */
188
	public function schedule_cron( $timestamp, $cron_schedule, $hook, $args = array(), $group = '' ) {
189
		return as_schedule_cron_action( $timestamp, $cron_schedule, $hook, $args, $group );
190
	}
191
192
	/**
193
	 * Dequeue all actions with a matching hook (and optionally matching args and group) so they are not run.
194
	 *
195
	 * Any recurring actions with a matching hook will also be cancelled, not just the next scheduled action.
196
	 *
197
	 * Technically, one action in a recurring or Cron action is scheduled at any one point in time. The next
198
	 * in the sequence is scheduled after the previous one is run, so only the next scheduled action needs to
199
	 * be cancelled/dequeued to stop the sequence.
200
	 *
201
	 * @param string $hook The hook that the job will trigger.
202
	 * @param array  $args Args that would have been passed to the job.
203
	 * @param string $group Group name.
204
	 */
205
	public function cancel( $hook, $args = array(), $group = '' ) {
206
		as_unschedule_action( $hook, $args, $group );
207
	}
208
209
	/**
210
	 * Get the date and time for the next scheduled occurence of an action with a given hook
211
	 * (an optionally that matches certain args and group), if any.
212
	 *
213
	 * @param string $hook Hook name.
214
	 * @param array  $args Arguments.
215
	 * @param string $group Group name.
216
	 * @return time|null The date and time for the next occurrence, or null if there is no pending, scheduled action for the given hook.
0 ignored issues
show
Bug introduced by
The type time was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
217
	 */
218
	public function get_next( $hook, $args = null, $group = '' ) {
219
220
		$next_timestamp = as_next_scheduled_action( $hook, $args, $group );
221
222
		if ( $next_timestamp ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $next_timestamp of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
223
			return $next_timestamp;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $next_timestamp returns the type integer which is incompatible with the documented return type null|time.
Loading history...
224
		}
225
226
		return null;
227
	}
228
229
	/**
230
	 * Find scheduled actions
231
	 *
232
	 * @param array  $args Possible arguments, with their default values:
233
	 *        'hook' => '' - the name of the action that will be triggered
234
	 *        'args' => null - the args array that will be passed with the action
235
	 *        'date' => null - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
236
	 *        'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='
237
	 *        'modified' => null - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
238
	 *        'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='
239
	 *        'group' => '' - the group the action belongs to
240
	 *        'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING
241
	 *        'claimed' => null - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID
242
	 *        'per_page' => 5 - Number of results to return
243
	 *        'offset' => 0
244
	 *        'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date'
245
	 *        'order' => 'ASC'.
246
	 *
247
	 * @param string $return_format OBJECT, ARRAY_A, or ids.
248
	 * @return array
249
	 */
250
	public function search( $args = array(), $return_format = OBJECT ) {
0 ignored issues
show
Bug introduced by
The constant OBJECT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
251
		return as_get_scheduled_actions( $args, $return_format );
252
	}
253
}
254