File tree Expand file tree Collapse file tree 2 files changed +63
-2
lines changed
Expand file tree Collapse file tree 2 files changed +63
-2
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ require __DIR__ . '/../vendor/autoload.php ' ;
6+
7+ use Revolt \EventLoop ;
8+
9+ \register_shutdown_function (function (): void {
10+ \register_shutdown_function (function (): void {
11+ EventLoop::defer (function (): void {
12+ print 'Shutdown function registered within pre-loop-run shutdown function ' . PHP_EOL ;
13+ });
14+ });
15+
16+
17+ EventLoop::defer (function (): void {
18+ print 'Shutdown function registered before EventLoop::run() ' . PHP_EOL ;
19+ });
20+ });
21+
22+ EventLoop::run ();
23+
24+ \register_shutdown_function (function (): void {
25+ \register_shutdown_function (function (): void {
26+ EventLoop::defer (function (): void {
27+ print 'Shutdown function registered within post-loop-run shutdown function ' . PHP_EOL ;
28+ });
29+ });
30+
31+ EventLoop::defer (function (): void {
32+ print 'Shutdown function registered after EventLoop::run() ' . PHP_EOL ;
33+ });
34+ });
35+
36+ print 'End of script ' . PHP_EOL ;
Original file line number Diff line number Diff line change @@ -28,8 +28,12 @@ final class EventLoop
2828 public static function setDriver (Driver $ driver ): void
2929 {
3030 /** @psalm-suppress RedundantPropertyInitializationCheck, RedundantCondition */
31- if (isset (self ::$ driver ) && self ::$ driver ->isRunning ()) {
32- throw new \Error ("Can't swap the event loop driver while the driver is running " );
31+ if (isset (self ::$ driver )) {
32+ if (self ::$ driver ->isRunning ()) {
33+ throw new \Error ("Can't swap the event loop driver while the driver is running " );
34+ }
35+ } else {
36+ \register_shutdown_function (self ::onShutdown (...), 0 );
3337 }
3438
3539 try {
@@ -67,6 +71,27 @@ protected function now(): float
6771 }
6872 }
6973
74+ private static function onShutdown (int $ invocationCount ): void
75+ {
76+ $ driver = self ::getDriver ();
77+
78+ $ pending = false ;
79+ foreach ($ driver ->getIdentifiers () as $ identifier ) {
80+ if ($ driver ->isEnabled ($ identifier ) && $ driver ->isReferenced ($ identifier )) {
81+ $ pending = true ;
82+ break ;
83+ }
84+ }
85+
86+ if ($ pending ) {
87+ $ driver ->run ();
88+ }
89+
90+ if (!$ invocationCount ++ || $ pending ) {
91+ \register_shutdown_function (self ::onShutdown (...), $ invocationCount );
92+ }
93+ }
94+
7095 /**
7196 * Queue a microtask.
7297 *
You can’t perform that action at this time.
0 commit comments