Skip to content

Commit b7cd3ae

Browse files
committed
Resolve #142 by adding a run() method
1 parent 5249aa6 commit b7cd3ae

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/Loop.php

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ final class Loop
4343
public static function setFactory(DriverFactory $factory = null)
4444
{
4545
if (self::$level > 0) {
46-
throw new \RuntimeException("Setting a new factory while running isn't allowed!");
46+
throw new \RuntimeException("Setting a new factory while running isn't allowed.");
4747
}
4848

4949
self::$factory = $factory;
@@ -82,6 +82,31 @@ public static function execute(callable $callback, Driver $driver = null)
8282
}
8383
}
8484

85+
/**
86+
* Run an unscoped loop.
87+
*
88+
* When possible, execute() SHOULD be preferred over run() for more explicit scoping.
89+
*
90+
* @return void
91+
*
92+
* @see \AsyncInterop\Loop::run()
93+
*/
94+
public static function run()
95+
{
96+
if (self::$level > 0) {
97+
throw new \RuntimeException("The loop can only be run while not yet running.");
98+
}
99+
100+
$driver = self::$driver ?: self::get();
101+
self::$level++;
102+
103+
try {
104+
$driver->run();
105+
} finally {
106+
self::$level--;
107+
}
108+
}
109+
85110
/**
86111
* Create a new driver if a factory is present, otherwise throw.
87112
*
@@ -430,3 +455,10 @@ private function __construct()
430455
// intentionally left blank
431456
}
432457
}
458+
459+
// Reset the $level in order to be able to use ::run() inside a shutdown handler
460+
$f = function()
461+
{
462+
self::$level = 0;
463+
};
464+
register_shutdown_function($f->bindTo(null, Loop::class));

0 commit comments

Comments
 (0)