-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCronJob.php
More file actions
248 lines (212 loc) · 6.24 KB
/
CronJob.php
File metadata and controls
248 lines (212 loc) · 6.24 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
<?php
/**
* COPYRIGHT NOTICE
* Copyright (c) 2023 Neue Rituale GbR
* @author NR <code@neuerituale.com>
*/
namespace ProcessWire;
use Exception;
class CronJob extends WireData {
const errorLog = 'cronjobs-errors';
const cronjobCacheNs = 'CronJob';
const triggerNever = 1;
const triggerAuto = 2;
const triggerLazy = 4;
const triggerForce = 8;
const triggerError = 16;
const timingInit = 1;
const timingReady = 2;
public function __construct() {
parent::__construct();
$this->reset();
}
/**
* Reset Cron object
* @return $this
*/
public function reset(): CronJob {
$this->data = [];
$this->setArray([
'name' => '',
'callback' => function() {},
'lazyCron' => null,
'ns' => null,
'timing' => self::timingReady,
'user' => null,
'notes' => [],
'lastRun' => 0,
'disabled' => false,
'trigger' => self::triggerNever,
'lastError' => ''
]);
return $this;
}
/**
* Set
* @param $key
* @param $value
* @return CronJob
*/
public function set($key, $value): CronJob {
$sanitizer = wire()->sanitizer;
if($key === 'name' && !empty($value)) {
$value = $sanitizer->pascalCase($value);
// load last run from cache
$data = wire()->cache->getFor(
self::cronjobCacheNs,
$sanitizer->pascalCase($value),
WireCache::expireNever
);
if(is_array($data) && count($data) >= 2) {
$this->data['lastRun'] = (int) $data[0]; // set quietly
$this->data['trigger'] = (int) $data[1]; // set quietly
$this->data['lastError'] = $data[2] ?? ''; // set quietly
}
}
else if($key === 'trigger') {
$value = (int) $value;
}
else if($key === 'ns') {
$value = $sanitizer->pagePathName($value);
}
else if($key === 'user') {
if(empty($value)) {
$value = null;
} else {
$search = $value;
if(!$value instanceof User) $value = wire()->users->get($value);
if(!$value->id) {
$this->disabled = true;
$this->addNote(sprintf($this->_('User "%s" not found'), $search));
$value = null;
}
}
}
else if($key === 'lastRun') {
// persist value
$value = (int) $value;
if($value > 0) {
wire()->cache->saveFor(
self::cronjobCacheNs,
$sanitizer->pascalCase($this->name),
[$value, $this->trigger, $this->lastError],
WireCache::expireNever
);
}
}
return parent::set($key, $value);
}
/**
* @param $key
* @return mixed|string|null
*/
public function get($key) {
if($key === 'triggerStr') {
return match($this->trigger) {
self::triggerAuto => $this->_('Auto'),
self::triggerLazy => $this->_('Lazy'),
self::triggerForce => $this->_('Manual'),
self::triggerError => $this->_('Error'),
default => __('Unknown')
};
}
else if($key === 'timingStr') {
return match($this->timing) {
self::timingInit => $this->_('onInit'),
self::timingReady => $this->_('onReady'),
default => __('Unknown')
};
}
else if($key === 'lazyCron' && !empty($this->ns)) {
return null;
}
else if($key === 'callback') {
$callback = $this->data['callback'];
return is_callable($callback)
? $callback
: function () { throw new \Exception('Callback is not callable'); };
}
return parent::get($key);
}
/**
* Add a note to notes
*
* @param $note
* @return $this
*/
public function addNote($note): CronJob {
$notes = $this->notes;
$notes[] = $note;
$this->set('notes', $notes);
return $this;
}
/**
* Update last run to current time
* @return void
*/
public function updateLastRun(): void {
$this->lastRun = time();
}
/**
* get Path
* @return string
*/
public function getPath(): string {
return $this->ns ? (trim($this->ns, '/') . '/') : '';
}
/**
* Execute the cron job callback
* @param int $successTrigger
* @return bool
*/
private function execute(int $successTrigger): bool {
$previousUser = null;
if($this->user instanceof User) {
$previousUser = wire()->user;
wire()->users->setCurrentUser($this->user);
}
try {
call_user_func_array($this->callback, [$this]);
$this->trigger = $successTrigger;
$this->set('lastError', '')->updateLastRun();
return true;
}
catch(Exception $exception) {
wire()->log(
sprintf($this->_('CronError in "%1$s": %2$s'), $this->name, $exception->getMessage()),
['name' => self::errorLog]
);
$this
->set('trigger', self::triggerError)
->set('lastError', $exception->getMessage())
->updateLastRun();
return false;
}
finally {
if($previousUser) wire()->users->setCurrentUser($previousUser);
}
}
/**
* Run cron job
* @param bool $force
* @return bool|void
* @throws WireException
*/
public function run(bool $force = false) {
// skip invalid & disabled
if(
!is_callable($this->callback) ||
($this->disabled && !$force)
) return false;
// via lazy cron
if($this->lazyCron && !$force) {
$cron = $this;
wire()->addHook($this->lazyCron, function() use($cron) {
return $cron->execute(self::triggerLazy);
});
return;
}
// every time or force
return $this->execute($force ? self::triggerForce : self::triggerAuto);
}
}