-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphpasync.php
More file actions
294 lines (249 loc) · 7.65 KB
/
phpasync.php
File metadata and controls
294 lines (249 loc) · 7.65 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
<?php
/**
* Manages asynchronous tasks with priorities.
*
* @package AsyncManager
* @author GLOBUS.studio <admin@globus.studio>
*/
use Fiber\Fiber;
class AsyncManager
{
private static $tasks = [];
public static function addTask(Async $task, int $priority = 0)
{
self::$tasks[] = [
'task' => $task,
'priority' => $priority
];
usort(self::$tasks, function ($a, $b) {
return $b['priority'] - $a['priority'];
});
}
public static function runTasks()
{
while (count(self::$tasks) > 0) {
$task = array_shift(self::$tasks)['task'];
$task->start();
}
}
public static function cancelAllOtherTasks(Async $completedTask) {
foreach (self::$tasks as $taskInfo) {
$task = $taskInfo['task'];
if ($task !== $completedTask) {
$task->cancel();
}
}
}
}
/**
* Represents an asynchronous task.
*
* Allows to execute operations asynchronously using fibers, manage their states,
* and handle results or exceptions using event-driven approach.
*
* @package Async
* @author GLOBUS.studio <admin@globus.studio>
*/
class Async {
private $fiber;
private $result;
private $error;
private $listeners = [];
private $startTime;
private $hasTimeout = false;
private $isCancelled = false;
/**
* Initializes a new asynchronous task.
*
* @param callable $callback The operation to be executed asynchronously.
*/
public function __construct(callable $callback) {
$this->startTime = microtime(true);
$this->fiber = new Fiber(function () use ($callback) {
try {
while (!$this->isCancelled) {
$this->result = $callback($this);
if ($this->hasTimeout && (microtime(true) - $this->startTime) > $this->hasTimeout) {
throw new Exception('Operation timed out.');
}
if (!$this->isCancelled) {
$this->emit('resolve', $this->result);
}
}
} catch (Throwable $e) {
$this->error = $e;
$this->emit('reject', $this->error);
} finally {
$this->emit('finally');
}
});
}
/**
* Awaits the completion of the asynchronous task.
*
* @return mixed The result of the asynchronous operation.
* @throws Exception If operation times out.
*/
public function await(): mixed {
if ($this->hasTimeout && (microtime(true) - $this->startTime) > $this->hasTimeout) {
throw new Exception('Operation timed out.');
}
$this->fiber->start();
if ($this->error) {
throw $this->error;
}
return $this->result;
}
/**
* Registers a callback to be called when the asynchronous task is fulfilled.
*
* @param callable $onFulfilled Callback to be executed on task completion.
* @param callable|null $onRejected Optional callback to be executed on task failure.
* @return self Returns the current Async instance.
*/
public function then(callable $onFulfilled, callable $onRejected = null) {
$this->on('resolve', $onFulfilled);
if ($onRejected) {
$this->on('reject', $onRejected);
}
return $this;
}
/**
* Registers a callback to be called when the asynchronous task is rejected.
*
* @param callable $onRejected Callback to be executed on task failure.
* @return self Returns the current Async instance.
*/
public function catch(callable $onRejected) {
$this->on('reject', $onRejected);
return $this;
}
/**
* Registers a callback to be called regardless of the asynchronous task's outcome.
*
* @param callable $callback Callback to be executed after task completion or failure.
* @return self Returns the current Async instance.
*/
public function finally(callable $callback) {
$this->on('finally', $callback);
return $this;
}
/**
* Registers an event listener for a specific event.
*
* @param string $event The event name.
* @param callable $listener The callback to be executed when the event is triggered.
* @return self Returns the current Async instance.
*/
public function on(string $event, callable $listener) {
$this->listeners[$event][] = $listener;
return $this;
}
/**
* Emits/triggers a specified event with the provided data.
*
* @param string $event The event name to trigger.
* @param mixed $data Optional data to be passed to the event listeners.
* @return void
*/
private function emit(string $event, $data = null) {
if (!isset($this->listeners[$event])) {
return;
}
foreach ($this->listeners[$event] as $listener) {
$listener($data);
}
}
/**
* Sets a timeout for the asynchronous operation.
*
* @param int $seconds The number of seconds before the operation times out.
* @return self Returns the current Async instance.
*/
public function timeout(int $seconds) {
$this->hasTimeout = $seconds;
return $this;
}
/**
* Awaits and returns results of all provided asynchronous tasks.
*
* @param array $tasks An array of Async tasks.
* @return array The results of the asynchronous tasks.
*/
public static function all(array $tasks): array {
$results = [];
foreach ($tasks as $key => $task) {
if ($task instanceof self) {
$results[$key] = $task->await();
}
}
return $results;
}
/**
* Awaits and returns the result of the first completed asynchronous task.
*
* @param array $tasks An array of Async tasks.
* @return mixed The result of the first completed task.
*/
public static function race(array $tasks) {
foreach ($tasks as $task) {
if ($task instanceof self) {
$result = $task->await();
AsyncManager::cancelAllOtherTasks($task);
return $result;
}
}
return null;
}
/**
* Cancels the asynchronous task.
*
* @return void
*/
public function cancel() {
$this->isCancelled = true;
$this->emit('cancel');
}
/**
* Registers a callback to be called to report progress of the asynchronous task.
*
* @param callable $callback Callback to be executed to report progress.
* @return self Returns the current Async instance.
*/
public function onProgress(callable $callback) {
return $this->on('progress', $callback);
}
/**
* Reports progress of the asynchronous task.
*
* @param mixed $data Data about the progress.
* @return void
*/
public function progress($data) {
$this->emit('progress', $data);
}
private $isStarted = false;
/**
* Starts the asynchronous task.
*
* @return void
*/
public function start()
{
if (!$this->isStarted) {
$this->isStarted = true;
$this->fiber->start();
}
}
/**
* Sets the priority for the asynchronous task.
*
* @param int $priority The priority level.
* @return self Returns the current Async instance.
*/
public function setPriority(int $priority)
{
AsyncManager::addTask($this, $priority);
return $this;
}
}