From d4fc8ce7b35d9626389d43c051c40072112f2cf1 Mon Sep 17 00:00:00 2001 From: Niklas Keller Date: Fri, 2 Aug 2019 22:09:38 +0200 Subject: [PATCH] Add CombinedCancellationToken Implementation has been used in http-client before. --- lib/CombinedCancellationToken.php | 79 +++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 lib/CombinedCancellationToken.php diff --git a/lib/CombinedCancellationToken.php b/lib/CombinedCancellationToken.php new file mode 100644 index 0000000..a5a6463 --- /dev/null +++ b/lib/CombinedCancellationToken.php @@ -0,0 +1,79 @@ +subscribe(function ($exception) { + $this->exception = $exception; + + $callbacks = $this->callbacks; + $this->callbacks = []; + + foreach ($callbacks as $callback) { + asyncCall($callback, $this->exception); + } + }); + + $this->tokens[] = [$token, $id]; + } + } + + public function __destruct() + { + foreach ($this->tokens as [$token, $id]) { + /** @var CancellationToken $token */ + $token->unsubscribe($id); + } + } + + /** @inheritdoc */ + public function subscribe(callable $callback): string + { + $id = $this->nextId++; + + if ($this->exception) { + asyncCall($callback, $this->exception); + } else { + $this->callbacks[$id] = $callback; + } + + return $id; + } + + /** @inheritdoc */ + public function unsubscribe(string $id) + { + unset($this->callbacks[$id]); + } + + /** @inheritdoc */ + public function isRequested(): bool + { + foreach ($this->tokens as [$token]) { + if ($token->isRequested()) { + return true; + } + } + + return false; + } + + /** @inheritdoc */ + public function throwIfRequested() + { + foreach ($this->tokens as [$token]) { + $token->throwIfRequested(); + } + } +} +