|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace mpyw\Co\Internal; |
|
4
|
|
|
use mpyw\Co\AllFailedException; |
|
5
|
|
|
use mpyw\Co\CoInterface; |
|
6
|
|
|
|
|
7
|
|
|
class ControlUtils |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Executed by Co::any() or Co::race(). |
|
11
|
|
|
* @param mixed $value |
|
12
|
|
|
* @param callable $filter self::reverse or self::fail. |
|
13
|
|
|
* @param string $message Used for failure. |
|
14
|
|
|
* @return \Generator |
|
15
|
|
|
*/ |
|
16
|
7 |
|
public static function anyOrRace($value, callable $filter, $message) |
|
17
|
7 |
|
{ |
|
18
|
7 |
|
$value = YieldableUtils::normalize($value); |
|
19
|
7 |
|
$yieldables = YieldableUtils::getYieldables($value); |
|
20
|
7 |
|
$wrapper = self::getWrapperGenerator($yieldables, $filter); |
|
21
|
|
|
try { |
|
22
|
7 |
|
$results = (yield $wrapper); |
|
23
|
4 |
|
} catch (ControlException $e) { |
|
24
|
3 |
|
yield CoInterface::RETURN_WITH => $e->getValue(); |
|
25
|
|
|
} |
|
26
|
3 |
|
$apply = YieldableUtils::getApplier($value, $yieldables); |
|
27
|
3 |
|
throw new AllFailedException($message, 0, $apply($results)); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Wrap yieldables with specified filter function. |
|
32
|
|
|
* @param array $yieldables |
|
33
|
|
|
* @param callable $filter self::reverse or self::fail. |
|
34
|
|
|
* @return \Generator |
|
35
|
|
|
*/ |
|
36
|
7 |
|
public static function getWrapperGenerator(array $yieldables, callable $filter) |
|
37
|
7 |
|
{ |
|
38
|
7 |
|
$gens = []; |
|
39
|
7 |
|
foreach ($yieldables as $yieldable) { |
|
40
|
5 |
|
$gens[(string)$yieldable['value']] = $filter($yieldable['value']); |
|
41
|
|
|
} |
|
42
|
7 |
|
yield CoInterface::RETURN_WITH => (yield $gens); |
|
43
|
|
|
// @codeCoverageIgnoreStart |
|
44
|
|
|
} |
|
45
|
|
|
// @codeCoverageIgnoreEnd |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Handle success as ControlException, failure as resolved. |
|
49
|
|
|
* @param mixed $yieldable |
|
50
|
|
|
* @return \Generator |
|
51
|
|
|
*/ |
|
52
|
3 |
|
public static function reverse($yieldable) |
|
53
|
3 |
|
{ |
|
54
|
|
|
try { |
|
55
|
3 |
|
$result = (yield $yieldable); |
|
56
|
2 |
|
} catch (\RuntimeException $e) { |
|
57
|
2 |
|
yield CoInterface::RETURN_WITH => $e; |
|
58
|
|
|
} |
|
59
|
2 |
|
throw new ControlException($result); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Handle success as ControlException. |
|
64
|
|
|
* @param mixed $yieldable |
|
65
|
|
|
* @return \Generator |
|
66
|
|
|
*/ |
|
67
|
2 |
|
public static function fail($yieldable) |
|
68
|
2 |
|
{ |
|
69
|
2 |
|
throw new ControlException(yield $yieldable); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|