From b7cd3aebb7a7703ec95b6f10f27da6a26355a147 Mon Sep 17 00:00:00 2001 From: Bob Weinand Date: Sun, 29 Jan 2017 20:45:54 +0100 Subject: [PATCH 1/2] Resolve #142 by adding a run() method --- src/Loop.php | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Loop.php b/src/Loop.php index 76f54d3..6bf1c81 100644 --- a/src/Loop.php +++ b/src/Loop.php @@ -43,7 +43,7 @@ final class Loop public static function setFactory(DriverFactory $factory = null) { if (self::$level > 0) { - throw new \RuntimeException("Setting a new factory while running isn't allowed!"); + throw new \RuntimeException("Setting a new factory while running isn't allowed."); } self::$factory = $factory; @@ -82,6 +82,31 @@ public static function execute(callable $callback, Driver $driver = null) } } + /** + * Run an unscoped loop. + * + * When possible, execute() SHOULD be preferred over run() for more explicit scoping. + * + * @return void + * + * @see \AsyncInterop\Loop::run() + */ + public static function run() + { + if (self::$level > 0) { + throw new \RuntimeException("The loop can only be run while not yet running."); + } + + $driver = self::$driver ?: self::get(); + self::$level++; + + try { + $driver->run(); + } finally { + self::$level--; + } + } + /** * Create a new driver if a factory is present, otherwise throw. * @@ -430,3 +455,10 @@ private function __construct() // intentionally left blank } } + +// Reset the $level in order to be able to use ::run() inside a shutdown handler +$f = function() +{ + self::$level = 0; +}; +register_shutdown_function($f->bindTo(null, Loop::class)); From 5cae165369522a7875d3ba0b7c2a905d9bfb48df Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Mon, 30 Jan 2017 10:58:57 -0600 Subject: [PATCH 2/2] Drop level requirement in run --- src/Loop.php | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/src/Loop.php b/src/Loop.php index 6bf1c81..0d7d303 100644 --- a/src/Loop.php +++ b/src/Loop.php @@ -89,14 +89,10 @@ public static function execute(callable $callback, Driver $driver = null) * * @return void * - * @see \AsyncInterop\Loop::run() + * @see \AsyncInterop\Loop\Driver::run() */ public static function run() { - if (self::$level > 0) { - throw new \RuntimeException("The loop can only be run while not yet running."); - } - $driver = self::$driver ?: self::get(); self::$level++; @@ -455,10 +451,3 @@ private function __construct() // intentionally left blank } } - -// Reset the $level in order to be able to use ::run() inside a shutdown handler -$f = function() -{ - self::$level = 0; -}; -register_shutdown_function($f->bindTo(null, Loop::class));