-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathReadableStreamChain.php
93 lines (73 loc) · 1.96 KB
/
ReadableStreamChain.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php declare(strict_types=1);
namespace Amp\ByteStream;
use Amp\Cancellation;
use Amp\DeferredFuture;
use Amp\ForbidCloning;
use Amp\ForbidSerialization;
/**
* @implements \IteratorAggregate<int, string>
*/
final class ReadableStreamChain implements ReadableStream, \IteratorAggregate
{
use ReadableStreamIteratorAggregate;
use ForbidCloning;
use ForbidSerialization;
/** @var ReadableStream[] */
private array $sources;
private bool $reading = false;
private readonly DeferredFuture $onClose;
public function __construct(ReadableStream ...$sources)
{
$this->sources = $sources;
$this->onClose = new DeferredFuture;
if (empty($this->sources)) {
$this->close();
}
}
public function read(?Cancellation $cancellation = null): ?string
{
if ($this->reading) {
throw new PendingReadError;
}
if (!$this->sources) {
return null;
}
$this->reading = true;
try {
while ($this->sources) {
$chunk = $this->sources[0]->read($cancellation);
if ($chunk === null) {
\array_shift($this->sources);
continue;
}
return $chunk;
}
return null;
} finally {
$this->reading = false;
}
}
public function isReadable(): bool
{
return !empty($this->sources);
}
public function close(): void
{
$sources = $this->sources;
$this->sources = [];
foreach ($sources as $source) {
$source->close();
}
if (!$this->onClose->isComplete()) {
$this->onClose->complete();
}
}
public function isClosed(): bool
{
return !$this->isReadable();
}
public function onClose(\Closure $onClose): void
{
$this->onClose->getFuture()->finally($onClose);
}
}