1 | <?php |
||
2 | /** |
||
3 | * Race |
||
4 | * User: moyo |
||
5 | * Date: 04/08/2017 |
||
6 | * Time: 12:26 AM |
||
7 | */ |
||
8 | |||
9 | namespace Carno\Promise\Features; |
||
10 | |||
11 | use Carno\Promise\Exception\RacingLoser; |
||
12 | use Carno\Promise\Promise; |
||
13 | use Carno\Promise\Promised; |
||
14 | use Carno\Promise\Stacked; |
||
15 | use Throwable; |
||
16 | |||
17 | trait Race |
||
18 | { |
||
19 | /** |
||
20 | * @param Promised ...$promises |
||
21 | * @return Promised |
||
22 | */ |
||
23 | public static function race(Promised ...$promises) : Promised |
||
24 | { |
||
25 | /** |
||
26 | * @var Promise $race |
||
27 | */ |
||
28 | |||
29 | $race = Promise::deferred(); |
||
30 | |||
31 | $sid = Stacked::in(...$promises); |
||
32 | |||
33 | foreach ($promises as $promise) { |
||
34 | $promise->then(static function (...$args) use ($race, $sid) { |
||
35 | if ($race->pended()) { |
||
36 | $race->resolve(...$args); |
||
37 | $race->rpInterrupt($sid); |
||
38 | } |
||
39 | }, static function (...$args) use ($race) { |
||
40 | if ($race->pended()) { |
||
41 | $race->reject(...$args); |
||
42 | } |
||
43 | }); |
||
44 | } |
||
45 | |||
46 | $race->then(null, static function (...$args) use ($race, $sid) { |
||
47 | $race->rpInterrupt($sid, $race->rpException(...$args)); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
48 | }); |
||
49 | |||
50 | return $race; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @param int $sid |
||
55 | * @param Throwable $e |
||
56 | */ |
||
57 | private function rpInterrupt(int $sid, Throwable $e = null) : void |
||
58 | { |
||
59 | foreach (Stacked::out($sid) as $promised) { |
||
60 | if ($promised->pended()) { |
||
61 | $e ? $promised->throw($e) : $promised->reject(); |
||
62 | } |
||
63 | } |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * @param mixed $test |
||
68 | * @return Throwable |
||
69 | */ |
||
70 | private function rpException($test = null) : Throwable |
||
71 | { |
||
72 | return $test instanceof Throwable ? $test : new RacingLoser(); |
||
73 | } |
||
74 | } |
||
75 |