Debian Codegraph @

vendor/react/async/src/SimpleFiber.php

raw
1 <?php
2
3 namespace React\Async;
4
5 use React\EventLoop\Loop;
6
7 /**
8 * @internal
9 */
10 final class SimpleFiber implements FiberInterface
11 {
12 /** @var ?\Fiber<void,void,void,callable(): mixed> */
13 private static ?\Fiber $scheduler = null;
14
15 private static ?\Closure $suspend = null;
16
17 /** @var ?\Fiber<mixed,mixed,mixed,mixed> */
18 private ?\Fiber $fiber = null;
19
20 public function __construct()
21 {
22 $this->fiber = \Fiber::getCurrent();
23 }
24
25 public function resume(mixed $value): void
26 {
27 if ($this->fiber !== null) {
28 $this->fiber->resume($value);
29 } else {
30 self::$suspend = static fn() => $value;
31 }
32
33 if (self::$suspend !== null && \Fiber::getCurrent() === self::$scheduler) {
34 $suspend = self::$suspend;
35 self::$suspend = null;
36
37 \Fiber::suspend($suspend);
38 }
39 }
40
41 public function throw(\Throwable $throwable): void
42 {
43 if ($this->fiber !== null) {
44 $this->fiber->throw($throwable);
45 } else {
46 self::$suspend = static fn() => throw $throwable;
47 }
48
49 if (self::$suspend !== null && \Fiber::getCurrent() === self::$scheduler) {
50 $suspend = self::$suspend;
51 self::$suspend = null;
52
53 \Fiber::suspend($suspend);
54 }
55 }
56
57 public function suspend(): mixed
58 {
59 if ($this->fiber === null) {
60 if (self::$scheduler === null || self::$scheduler->isTerminated()) {
61 self::$scheduler = new \Fiber(static fn() => Loop::run());
62 // Run event loop to completion on shutdown.
63 \register_shutdown_function(static function (): void {
64 assert(self::$scheduler instanceof \Fiber);
65 if (self::$scheduler->isSuspended()) {
66 self::$scheduler->resume();
67 }
68 });
69 }
70
71 $ret = (self::$scheduler->isStarted() ? self::$scheduler->resume() : self::$scheduler->start());
72 assert(\is_callable($ret));
73
74 return $ret();
75 }
76
77 return \Fiber::suspend();
78 }
79 }