1
0
mirror of https://github.com/danog/amp.git synced 2024-12-03 18:07:57 +01:00
amp/lib/CombinedCancellationToken.php

83 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Amp;
final class CombinedCancellationToken implements CancellationToken
{
/** @var array{0: CancellationToken, 1: string}[] */
2020-10-02 20:55:46 +02:00
private array $tokens = [];
2020-10-02 20:55:46 +02:00
private string $nextId = "a";
/** @var callable[] */
2020-10-02 20:55:46 +02:00
private array $callbacks = [];
2020-10-23 06:03:58 +02:00
private CancelledException $exception;
public function __construct(CancellationToken ...$tokens)
{
foreach ($tokens as $token) {
2020-10-23 06:03:58 +02:00
$id = $token->subscribe(function (CancelledException $exception): void {
$this->exception = $exception;
$callbacks = $this->callbacks;
$this->callbacks = [];
foreach ($callbacks as $callback) {
defer($callback, $this->exception);
}
});
$this->tokens[] = [$token, $id];
}
}
public function __destruct()
{
2020-10-25 21:44:01 +01:00
foreach ($this->tokens as [$token, $id]) {
/** @var CancellationToken $token */
$token->unsubscribe($id);
}
}
/** @inheritdoc */
public function subscribe(callable $callback): string
{
$id = $this->nextId++;
2020-10-23 06:03:58 +02:00
if (isset($this->exception)) {
defer($callback, $this->exception);
} else {
$this->callbacks[$id] = $callback;
}
return $id;
}
/** @inheritdoc */
public function unsubscribe(string $id): void
{
unset($this->callbacks[$id]);
}
/** @inheritdoc */
public function isRequested(): bool
{
2020-10-25 21:44:01 +01:00
foreach ($this->tokens as [$token]) {
if ($token->isRequested()) {
return true;
}
}
return false;
}
/** @inheritdoc */
public function throwIfRequested(): void
{
2020-10-25 21:44:01 +01:00
foreach ($this->tokens as [$token]) {
$token->throwIfRequested();
}
}
}