-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathSimpleFiber.php
More file actions
78 lines (63 loc) · 2.06 KB
/
SimpleFiber.php
File metadata and controls
78 lines (63 loc) · 2.06 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
<?php
namespace React\Async;
use React\EventLoop\Loop;
/**
* @internal
*/
final class SimpleFiber implements FiberInterface
{
private static ?\Fiber $scheduler = null;
private static ?\Closure $suspend = null;
private ?\Fiber $fiber = null;
public function __construct()
{
$this->fiber = \Fiber::getCurrent();
}
public function resume(mixed $value): void
{
if ($this->fiber !== null) {
$this->fiber->resume($value);
} else {
self::$suspend = static fn() => $value;
}
if (self::$suspend !== null && \Fiber::getCurrent() === self::$scheduler) {
$suspend = self::$suspend;
self::$suspend = null;
\Fiber::suspend($suspend);
}
}
public function throw(\Throwable $throwable): void
{
if ($this->fiber !== null) {
$this->fiber->throw($throwable);
} else {
self::$suspend = static fn() => throw $throwable;
}
if (self::$suspend !== null && \Fiber::getCurrent() === self::$scheduler) {
$suspend = self::$suspend;
self::$suspend = null;
\Fiber::suspend($suspend);
}
}
public function suspend(): mixed
{
if ($this->fiber === null) {
if (self::$scheduler === null || self::$scheduler->isTerminated()) {
self::$scheduler = new \Fiber(static fn() => Loop::run());
// Run event loop to completion on shutdown.
\register_shutdown_function(static function (): void {
if (self::$scheduler->isSuspended()) {
self::$scheduler->resume();
}
});
}
$ret = (self::$scheduler->isStarted() ? self::$scheduler->resume() : self::$scheduler->start());
assert(is_callable($ret));
Loop::stop();
self::$scheduler->resume();
assert(self::$scheduler->isTerminated());
return $ret();
}
return \Fiber::suspend();
}
}