-
Notifications
You must be signed in to change notification settings - Fork 3
/
functions.php
101 lines (82 loc) · 2.29 KB
/
functions.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
94
95
96
97
98
99
100
101
<?php
namespace Productsup\GuzzleReactBridge;
use Closure;
use GuzzleHttp\Promise\Promise;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use function GuzzleHttp\Promise\coroutine;
/**
* Run an action inside a fresh event loop
*
* Shortcut to create an event loop with default settings, that suits for most cases.
*
* @param callable $action
*
* @return void
*/
function run(callable $action)
{
$loop = Factory::create();
\GuzzleHttp\Promise\queue(new ReactTaskQueue($loop));
$loop->futureTick(function() use ($loop, $action){
$action($loop);
});
$loop->run();
}
/**
* Run a coroutine inside a fresh event loop
*
* Shortcut to create an event loop with default settings, that suits for most cases.
*
* @param callable $coroutine
*
* @return mixed
*/
function run_coroutine_fn(callable $coroutine)
{
$loop = Factory::create();
$coroutineFn = function () use ($loop, $coroutine) {
return $coroutine($loop);
};
\GuzzleHttp\Promise\queue(new ReactTaskQueue($loop));
$globalResult = null;
/** @var \Exception $globalError */
$globalError = null;
$loop->futureTick(function () use ($coroutineFn, &$globalResult, &$globalError) {
$coroutineInvocation = coroutine($coroutineFn)
->then(function ($result) use (&$globalResult) {
return $globalResult = $result;
})
->otherwise(function ($reason) use (&$globalError) {
$globalError = \GuzzleHttp\Promise\exception_for($reason);
// Reject it again, don't change the state.
return \GuzzleHttp\Promise\rejection_for($reason);
})
;
// Here we are, waiting for the coroutine (promise) to complete.
});
$loop->run();
// And check whether there is an exception or not...
if ($globalError) {
throw $globalError;
}
// TODO Support it.
return $globalResult;
}
/**
* "Concurrent sleep" using a timer.
*
* @param LoopInterface $loop
*
* @return Closure
*/
function sleep_fn(LoopInterface $loop)
{
return function ($interval) use ($loop) {
$promise = new Promise();
$loop->addTimer($interval, function () use ($promise) {
$promise->resolve(null);
});
return $promise;
};
}