-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask.php
More file actions
355 lines (342 loc) · 13.7 KB
/
Task.php
File metadata and controls
355 lines (342 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
<?php
declare(strict_types = 1);
namespace Simbiat\Cron;
use Simbiat\Database\Query;
use Simbiat\StringHelpers\Sanitize;
use function is_string, is_array;
/**
* Cron task object
* @noinspection ContractViolationInspection https://github.com/kalessil/phpinspectionsea/issues/1996
*/
class Task
{
use TraitForCron;
/**
* @var string Unique name of the task
*/
private(set) string $task_name = '';
/**
* @var string Name of the task
*/
private(set) string $function = '';
/**
* @var string|null Optional object reference
*/
private(set) ?string $object = null;
/**
* @var string|null Parameters to set for the object (passed to construct)
*/
private(set) ?string $parameters = '' {
/**
* @noinspection PhpMethodNamingConventionInspection https://youtrack.jetbrains.com/issue/WI-81560
*/
set (mixed $value) {
/** @noinspection IsEmptyFunctionUsageInspection We do not know what values to expect here, so this should be fine as a universal solution */
if (empty($value)) {
$this->parameters = null;
} elseif (is_array($value)) {
try {
$this->parameters = \json_encode($value, \JSON_THROW_ON_ERROR | \JSON_INVALID_UTF8_SUBSTITUTE | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION);
} catch (\Throwable) {
$this->parameters = null;
}
} elseif (is_string($value) && \json_validate($value)) {
$this->parameters = $value;
} else {
throw new \UnexpectedValueException('`parameters` is not an array or a valid JSON string');
}
}
}
/**
* @var string|null Expected (and allowed) return values
*/
private(set) ?string $returns = '' {
/**
* @noinspection PhpMethodNamingConventionInspection https://youtrack.jetbrains.com/issue/WI-81560
*/
set (mixed $value) {
/** @noinspection IsEmptyFunctionUsageInspection We do not know what values to expect here, so this should be fine as a universal solution */
if (empty($value)) {
$this->returns = null;
} elseif (is_array($value)) {
try {
$this->returns = \json_encode($value, \JSON_THROW_ON_ERROR | \JSON_INVALID_UTF8_SUBSTITUTE | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION);
} catch (\Throwable) {
$this->returns = null;
}
} elseif (is_string($value) && \json_validate($value)) {
$this->returns = $value;
} else {
throw new \UnexpectedValueException('`returns` is not an array or a valid JSON string');
}
}
}
/**
* @var int Maximum execution time
*/
private(set) int $max_time = 3600 {
/**
* @noinspection PhpMethodNamingConventionInspection https://youtrack.jetbrains.com/issue/WI-81560
*/
set {
$this->max_time = $value;
if ($this->max_time < 0) {
$this->max_time = 0;
}
}
}
/**
* @var int Minimal-allowed frequency (in seconds) at which a task instance can run. Does not apply to one-time jobs.
*/
private(set) int $min_frequency = 3600 {
/**
* @noinspection PhpMethodNamingConventionInspection https://youtrack.jetbrains.com/issue/WI-81560
*/
set {
$this->min_frequency = $value;
if ($this->min_frequency < 0) {
$this->min_frequency = 0;
}
}
}
/**
* @var int Custom number of seconds to reschedule a failed task instance for. 0 disables the functionality.
*/
private(set) int $retry = 3600 {
/**
* @noinspection PhpMethodNamingConventionInspection https://youtrack.jetbrains.com/issue/WI-81560
*/
set {
$this->retry = $value;
if ($this->retry < 0) {
$this->retry = 0;
}
}
}
/**
* @var bool Whether a task is system one or not
*/
private(set) bool $system = false;
/**
* @var bool Whether a task (and its task instances) is enabled
*/
private(set) bool $enabled = true;
/**
* @var string|null Description of the task
*/
private(set) ?string $description = null;
/**
* @var bool Whether a task was found in a database
*/
private(set) bool $found_in_db = false;
/**
* Create a Cron task object
*
* @param string $task_name If the name is not empty, settings will be attempts to be loaded from the database
* @param \PDO|null $dbh PDO object to use for database connection. If not provided, the class expects that the connection has already been established through `\Simbiat\Cron\Agent`.
* @param string $prefix Cron database prefix.
*/
public function __construct(string $task_name = '', \PDO|null $dbh = null, string $prefix = 'cron__')
{
$this->init($dbh, $prefix);
if (!Sanitize::whiteString($task_name ?? '')) {
$this->task_name = $task_name;
#Attempt to get settings from DB
$this->getFromDB();
}
}
/**
* Get task settings from database
*
* @return void
*/
private function getFromDB(): void
{
$settings = Query::query('SELECT * FROM `'.$this->prefix.'tasks` WHERE `task`=:name;', [':name' => $this->task_name], return: 'row');
if ($settings !== []) {
$this->settingsFromArray($settings);
if (Sanitize::whiteString($this->function ?? '')) {
throw new \UnexpectedValueException('Task has no assigned function');
}
$this->found_in_db = true;
}
}
/**
* Set task settings from associative array
*
* @return $this
*/
public function settingsFromArray(array $settings): self
{
foreach ($settings as $setting => $value) {
switch ($setting) {
case 'object':
/** @noinspection IsEmptyFunctionUsageInspection Valid use case, we don't know what's in the provided array */
if (empty($value)) {
$this->object = null;
} else {
$this->object = $value;
}
break;
case 'allowed_returns':
$this->returns = $value;
break;
case 'task':
$this->task_name = $value;
break;
case 'function':
case 'parameters':
case 'max_time':
case 'min_frequency':
case 'retry':
$this->{$setting} = $value;
break;
case 'enabled':
case 'system':
$this->{$setting} = (bool)$value;
break;
case 'description':
/** @noinspection IsEmptyFunctionUsageInspection Valid use case, we don't know what's in the provided array */
if (empty($value)) {
$this->description = null;
} else {
$this->description = $value;
}
break;
default:
#Do nothing
break;
}
}
return $this;
}
/**
* Add (or update) the task
*
* @return bool
*/
public function add(): bool
{
if (Sanitize::whiteString($this->task_name ?? '')) {
throw new \UnexpectedValueException('Task name is not set');
}
if (Sanitize::whiteString($this->function ?? '')) {
throw new \UnexpectedValueException('Function name is not set');
}
try {
$task_details_string = \json_encode($this, \JSON_THROW_ON_ERROR | \JSON_INVALID_UTF8_SUBSTITUTE | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION);
$result = Query::query('INSERT INTO `'.$this->prefix.'tasks` (`task`, `function`, `object`, `parameters`, `allowed_returns`, `max_time`, `min_frequency`, `retry`, `enabled`, `system`, `description`) VALUES (:task, :function, :object, :parameters, :returns, :max_time, :min_frequency, :retry, :enabled, :system, :desc) ON DUPLICATE KEY UPDATE `function`=:function, `object`=:object, `parameters`=:parameters, `allowed_returns`=:returns, `max_time`=:max_time, `min_frequency`=:min_frequency, `retry`=:retry, `description`=:desc;', [
':task' => [$this->task_name, 'string'],
':function' => [$this->function, 'string'],
':object' => [$this->object, (Sanitize::whiteString($this->object ?? '') ? 'null' : 'string')],
':parameters' => [$this->parameters, (Sanitize::whiteString($this->parameters ?? '') ? 'null' : 'string')],
':returns' => [$this->returns, (Sanitize::whiteString($this->returns ?? '') ? 'null' : 'string')],
':max_time' => [$this->max_time, 'int'],
':min_frequency' => [$this->min_frequency, 'int'],
':retry' => [$this->retry, 'int'],
':enabled' => [$this->enabled, 'bool'],
':system' => [$this->system, 'bool'],
':desc' => [$this->description, (Sanitize::whiteString($this->description ?? '') ? 'null' : 'string')],
], return: 'affected');
$this->getFromDB();
} catch (\Throwable $throwable) {
$this->log('Failed to add or update task with following details: '.$task_details_string.'.', EventTypes::TaskAddFail, error: $throwable);
return false;
}
#Log only if something was actually changed
if ($result > 0) {
$this->log('Added or updated task with following details: '.$task_details_string.'.', EventTypes::TaskAdd);
}
return true;
}
/**
* Delete the task if it's not a system one
*
* @return bool
*/
public function delete(): bool
{
if (Sanitize::whiteString($this->task_name ?? '')) {
throw new \UnexpectedValueException('Task name is not set');
}
try {
$result = Query::query('DELETE FROM `'.$this->prefix.'tasks` WHERE `task`=:task AND `system`=0;', [
':task' => [$this->task_name, 'string'],
], return: 'affected');
} catch (\Throwable $throwable) {
$this->log('Failed delete task `'.$this->task_name.'`.', EventTypes::TaskDeleteFail, error: $throwable);
return false;
}
#Log only if something was actually deleted
if ($result > 0) {
$this->found_in_db = false;
try {
#Try to delete the respective task instances as well
Query::query('DELETE FROM `'.$this->prefix.'schedule` WHERE `task`=:task AND `system`=0;', [
':task' => [$this->task_name, 'string'],
]);
} catch (\Throwable) {
#Do nothing, not critical
}
$this->log('Deleted task `'.$this->task_name.'`.', EventTypes::TaskDelete);
}
return true;
}
/**
* Set the task as a system one
* @return bool
*/
public function setSystem(): bool
{
if (Sanitize::whiteString($this->task_name ?? '')) {
throw new \UnexpectedValueException('Task name is not set');
}
if ($this->found_in_db) {
try {
$result = Query::query('UPDATE `'.$this->prefix.'tasks` SET `system`=1 WHERE `task`=:task AND `system`=0;', [
':task' => [$this->task_name, 'string'],
], return: 'affected');
} catch (\Throwable $throwable) {
$this->log('Failed to mark task `'.$this->task_name.'` as system one.', EventTypes::TaskToSystemFail, error: $throwable);
return false;
}
#Log only if something was actually changed
if ($result > 0) {
$this->system = true;
$this->log('Marked task `'.$this->task_name.'` as system one.', EventTypes::TaskToSystem);
}
return true;
}
return false;
}
/**
* Function to enable or disable the task and its instances
* @param bool $enabled Flag indicating whether we want to enable or disable the task
*
* @return bool
*/
public function setEnabled(bool $enabled = true): bool
{
if (Sanitize::whiteString($this->task_name ?? '')) {
throw new \UnexpectedValueException('Task name is not set');
}
if ($this->found_in_db) {
try {
$result = Query::query('UPDATE `'.$this->prefix.'tasks` SET `enabled`=:enabled WHERE `task`=:task;', [
':task' => [$this->task_name, 'string'],
':enabled' => [$enabled, 'bool'],
], return: 'affected');
} catch (\Throwable $throwable) {
$this->log('Failed to '.($enabled ? 'enable' : 'disable').' task.', ($enabled ? EventTypes::TaskEnableFail : EventTypes::TaskDisableFail), error: $throwable);
return false;
}
#Log only if something was actually changed
if ($result > 0) {
$this->enabled = $enabled;
$this->log(($enabled ? 'Enabled' : 'Disabled').' task.', ($enabled ? EventTypes::TaskEnable : EventTypes::TaskDisable));
}
return true;
}
return false;
}
}