1
0
mirror of https://github.com/danog/amp.git synced 2024-11-26 20:15:00 +01:00

Implement additional cancellation token methods

This commit is contained in:
Niklas Keller 2017-05-22 19:26:09 +02:00
parent 7e500548df
commit 5dad46f297
2 changed files with 29 additions and 0 deletions

View File

@ -29,4 +29,18 @@ interface CancellationToken {
* @return void
*/
public function unsubscribe(string $id);
/**
* Returns whether cancellation has been requested yet.
*
* @return bool
*/
public function isRequested(): bool;
/**
* Throws the `CancelledException` if cancellation has been requested, otherwise does nothing.
*
* @return void
*/
public function throwIfRequested();
}

View File

@ -44,8 +44,13 @@ final class CancellationTokenSource {
public function __construct() {
$this->token = new class($this->onCancel) implements CancellationToken {
/** @var string */
private $nextId = "a";
/** @var callable[] */
private $callbacks = [];
/** @var \Throwable|null */
private $exception = null;
public function __construct(&$onCancel) {
@ -95,6 +100,16 @@ final class CancellationTokenSource {
public function unsubscribe(string $id) {
unset($this->callbacks[$id]);
}
public function isRequested(): bool {
return isset($this->exception);
}
public function throwIfRequested() {
if (isset($this->exception)) {
throw $this->exception;
}
}
};
}