1
0
mirror of https://github.com/danog/amp.git synced 2024-11-30 04:29:08 +01:00
amp/lib/TimeoutCancellationToken.php

70 lines
1.4 KiB
PHP
Raw Normal View History

2017-06-13 19:41:47 +02:00
<?php
namespace Amp;
/**
* A TimeoutCancellationToken automatically requests cancellation after the timeout has elapsed.
*/
2018-06-18 20:00:01 +02:00
final class TimeoutCancellationToken implements CancellationToken
{
2017-06-13 19:41:47 +02:00
/** @var string */
private $watcher;
/** @var \Amp\CancellationToken */
private $token;
/**
* @param int $timeout Milliseconds until cancellation is requested.
*/
2018-06-18 20:00:01 +02:00
public function __construct(int $timeout)
{
2017-06-13 19:41:47 +02:00
$source = new CancellationTokenSource;
$this->token = $source->getToken();
$this->watcher = Loop::delay($timeout, static function () use ($source) {
$source->cancel(new TimeoutException);
});
Loop::unreference($this->watcher);
}
/**
* Cancels the delay watcher.
*/
2018-06-18 20:00:01 +02:00
public function __destruct()
{
2017-06-13 19:41:47 +02:00
Loop::cancel($this->watcher);
}
/**
* {@inheritdoc}
*/
2018-06-18 20:00:01 +02:00
public function subscribe(callable $callback): string
{
2017-06-13 19:41:47 +02:00
return $this->token->subscribe($callback);
}
/**
* {@inheritdoc}
*/
2018-06-18 20:00:01 +02:00
public function unsubscribe(string $id)
{
2017-06-13 19:41:47 +02:00
$this->token->unsubscribe($id);
}
/**
* {@inheritdoc}
*/
2018-06-18 20:00:01 +02:00
public function isRequested(): bool
{
2017-06-13 19:41:47 +02:00
return $this->token->isRequested();
}
/**
* {@inheritdoc}
*/
2018-06-18 20:00:01 +02:00
public function throwIfRequested()
{
2017-06-13 19:41:47 +02:00
$this->token->throwIfRequested();
}
}