|
14 | 14 |
|
15 | 15 | use React\ChildProcess\Process;
|
16 | 16 | use React\EventLoop\LoopInterface;
|
| 17 | +use React\Promise\Deferred; |
17 | 18 | use React\Promise\PromiseInterface;
|
18 | 19 |
|
19 |
| -use function React\Promise\reject; |
20 |
| -use function React\Promise\Stream\buffer; |
21 |
| - |
22 | 20 | const proc = __NAMESPACE__ . '\\proc';
|
23 | 21 |
|
24 | 22 | /**
|
|
33 | 31 | * @return PromiseInterface
|
34 | 32 | * @example
|
35 | 33 | *
|
36 |
| - * proc('php -r "echo 12;"') |
37 |
| - * => object(React\Promise\Promise) {} |
| 34 | + * proc('php -r "echo 12 . PHP_EOL;"') |
| 35 | + * ->then( |
| 36 | + * function ($result) { |
| 37 | + * echo $result; |
| 38 | + * } |
| 39 | + * ) |
| 40 | + * => 12 |
38 | 41 | */
|
39 | 42 | function proc(string $process, ?LoopInterface $loop = null): PromiseInterface
|
40 | 43 | {
|
41 |
| - $proc = new Process($process); |
| 44 | + $proc = new Process($process); |
| 45 | + $result = new Deferred(); |
42 | 46 | $proc->start($loop);
|
43 | 47 |
|
44 | 48 | if (!$proc->stdout->isReadable()) {
|
45 |
| - return reject( |
46 |
| - new \Exception(\sprintf('Could not process %s', $process)) |
| 49 | + $result->reject( |
| 50 | + new \Exception( |
| 51 | + \sprintf('Could not process "%s"', $process) |
| 52 | + ) |
47 | 53 | );
|
| 54 | + |
| 55 | + return $result; |
48 | 56 | }
|
49 | 57 |
|
50 |
| - return buffer($proc->stdout); |
| 58 | + $proc->stdout->on( |
| 59 | + 'data', |
| 60 | + function ($chunk) use (&$result) { |
| 61 | + $result->resolve($chunk); |
| 62 | + } |
| 63 | + ); |
| 64 | + |
| 65 | + // reject promise in the event of failure |
| 66 | + $proc->stdout->on( |
| 67 | + 'error', |
| 68 | + function (\Throwable $err) use (&$result, &$proc) { |
| 69 | + $result->reject($err); |
| 70 | + } |
| 71 | + ); |
| 72 | + |
| 73 | + // handle successful closure of the process stream |
| 74 | + $proc->stdout->on( |
| 75 | + 'end', |
| 76 | + function () use (&$result) { |
| 77 | + $result->resolve(true); |
| 78 | + } |
| 79 | + ); |
| 80 | + |
| 81 | + // handle unsuccessful closure of process stream |
| 82 | + $proc->stdout->on( |
| 83 | + 'close', |
| 84 | + function () use (&$result, $process) { |
| 85 | + $result->reject( |
| 86 | + new \Exception( |
| 87 | + \sprintf('Closed process "%s"', $process) |
| 88 | + ) |
| 89 | + ); |
| 90 | + } |
| 91 | + ); |
| 92 | + |
| 93 | + return $result->promise(); |
51 | 94 | }
|
0 commit comments