-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStrandWaitAll.php
More file actions
105 lines (88 loc) · 2.81 KB
/
StrandWaitAll.php
File metadata and controls
105 lines (88 loc) · 2.81 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
<?php
declare(strict_types=1); // @codeCoverageIgnore
namespace Recoil\Kernel;
use Recoil\Awaitable;
use Recoil\Listener;
use Recoil\Strand;
use Throwable;
/**
* Implementation of Api::all().
*/
final class StrandWaitAll implements Awaitable, Listener
{
public function __construct(SystemStrand ...$substrands)
{
$this->substrands = $substrands;
}
/**
* Attach a listener to this object.
*
* @param Listener $listener The object to resume when the work is complete.
*
* @return null
*/
public function await(Listener $listener)
{
if ($listener instanceof SystemStrand) {
$listener->setTerminator(function () {
foreach ($this->substrands as $strand) {
$strand->clearPrimaryListener();
$strand->terminate();
}
});
}
$this->listener = $listener;
foreach ($this->substrands as $substrand) {
$substrand->setPrimaryListener($this);
}
}
/**
* Send the result of a successful operation.
*
* @param mixed $value The operation result.
* @param Strand|null $strand The strand that produced this result upon exit, if any.
*/
public function send($value = null, Strand $strand = null)
{
assert($strand instanceof Strand, 'strand cannot be null');
assert(in_array($strand, $this->substrands, true), 'unknown strand');
$index = \array_search($strand, $this->substrands, true);
unset($this->substrands[$index]);
$this->values[$index] = $value;
if (empty($this->substrands)) {
$this->listener->send($this->values);
}
}
/**
* Send the result of an unsuccessful operation.
*
* @param Throwable $exception The operation result.
* @param Strand|null $strand The strand that produced this exception upon exit, if any.
*/
public function throw(Throwable $exception, Strand $strand = null)
{
assert($strand instanceof Strand, 'strand cannot be null');
assert(in_array($strand, $this->substrands, true), 'unknown strand');
foreach ($this->substrands as $s) {
if ($s !== $strand) {
$s->clearPrimaryListener();
$s->terminate();
}
}
$this->substrands = [];
$this->listener->throw($exception, $strand);
}
/**
* @var Listener|null The object to notify upon completion.
*/
private $listener;
/**
* @var array<SystemStrand> The strands to wait for.
*/
private $substrands;
/**
* @var array<integer, mixed> The results of the successful strands. Ordered
* by completion order, indexed by strand order.
*/
private $values = [];
}