Skip to content

Commit

Permalink
🚧 integrate new EventLoop with YieldPromise
Browse files Browse the repository at this point in the history
  • Loading branch information
matyo91 committed Apr 21, 2021
1 parent b19c9b2 commit 4de1766
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions src/Adapter/Swoole/EventLoop.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

namespace M6Web\Tornado\Adapter\Swoole;

use M6Web\Tornado\Adapter\Common\Internal\FailingPromiseCollection;
use M6Web\Tornado\Adapter\Swoole\Internal\SwooleDeferred;
use M6Web\Tornado\Adapter\Swoole\Internal\SwoolePromise;
use M6Web\Tornado\Adapter\Swoole\Internal\YieldPromise;
use M6Web\Tornado\Deferred;
use M6Web\Tornado\Promise;
use Swoole\Coroutine;
Expand All @@ -14,33 +12,47 @@

class EventLoop implements \M6Web\Tornado\EventLoop
{
private $cids;

public function __construct()
{
if (!extension_loaded('swoole')) {
throw new RuntimeException(
'SwoolePromise MUST running only in CLI mode with swoole extension.'
);
}

$this->cids = [];
}

/**
* {@inheritdoc}
*/
public function wait(Promise $promise)
{

$value = null;
$this->async((static function() use($promise, &$value): \Generator {
$value = yield $promise;
Event::exit();
})());
Event::wait();

return $value;
}

/**
* {@inheritdoc}
*/
public function async(\Generator $generator): Promise
{

$generatorPromise = new YieldPromise();
Coroutine::create(function() use($generator, $generatorPromise) {
while($generator->valid()) {
$promise = $generator->current();
$promise->yield();
$generator->send($promise->value());
}

$generatorPromise->resolve($generator->getReturn());
});

return $generatorPromise;
}

/**
Expand Down Expand Up @@ -86,15 +98,26 @@ public function promiseRejected(\Throwable $throwable): Promise
*/
public function idle(): Promise
{
$promise = new YieldPromise();
Coroutine::create(function() use($promise) {
$promise->resolve(null);
});

return $promise;
}

/**
* {@inheritdoc}
*/
public function delay(int $milliseconds): Promise
{
$promise = new YieldPromise();
Coroutine::create(function() use($milliseconds, $promise) {
Coroutine::sleep($milliseconds / 1000 /* ms -> s */);
$promise->resolve(null);
});

return $promise;
}

/**
Expand Down

0 comments on commit 4de1766

Please sign in to comment.