1
0
mirror of https://github.com/danog/file.git synced 2024-12-03 09:47:54 +01:00
file/lib/Internal/EioPoll.php

76 lines
1.8 KiB
PHP
Raw Normal View History

2017-06-20 05:58:11 +02:00
<?php
namespace Amp\File\Internal;
use Amp\CallableMaker;
2017-06-20 05:58:11 +02:00
use Amp\Loop;
use Amp\Promise;
2017-06-20 05:58:11 +02:00
class EioPoll {
use CallableMaker;
2017-06-20 05:58:11 +02:00
/** @var resource */
private static $stream;
2017-06-20 07:31:58 +02:00
2017-06-20 05:58:11 +02:00
/** @var string */
private $watcher;
2017-06-20 07:31:58 +02:00
2017-06-20 05:58:11 +02:00
/** @var int */
private $requests = 0;
2017-06-20 07:31:58 +02:00
/** @var callable */
private $onDone;
2017-06-20 05:58:11 +02:00
public function __construct() {
$this->onDone = $this->callableFromInstanceMethod("done");
2017-06-20 05:58:11 +02:00
if (!self::$stream) {
\eio_init();
self::$stream = \eio_get_event_stream();
}
$this->watcher = Loop::onReadable(self::$stream, static function () {
2017-06-20 05:58:11 +02:00
while (\eio_npending()) {
\eio_poll();
}
});
2017-06-20 07:31:58 +02:00
2017-06-20 05:58:11 +02:00
Loop::disable($this->watcher);
Loop::setState(self::class, new class($this->watcher) {
private $watcher;
private $driver;
public function __construct(string $watcher) {
$this->watcher = $watcher;
$this->driver = Loop::get();
}
public function __destruct() {
$this->driver->cancel($this->watcher);
// Ensure there are no active operations anymore. This is a safe-guard as some operations might not be
// finished on loop exit due to not being yielded. This also ensures a clean shutdown for these if PHP
// exists.
\eio_event_loop();
}
});
2017-06-20 05:58:11 +02:00
}
2017-06-20 07:31:58 +02:00
public function listen(Promise $promise) {
2017-06-20 05:58:11 +02:00
if ($this->requests++ === 0) {
Loop::enable($this->watcher);
}
$promise->onResolve($this->onDone);
2017-06-20 05:58:11 +02:00
}
2017-06-20 07:31:58 +02:00
private function done() {
2017-06-20 05:58:11 +02:00
if (--$this->requests === 0) {
Loop::disable($this->watcher);
}
2017-06-20 07:31:58 +02:00
\assert($this->requests >= 0);
2017-06-20 05:58:11 +02:00
}
2017-06-20 07:31:58 +02:00
}