|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Rx\React; |
| 4 | + |
| 5 | +use React\ChildProcess\Process; |
| 6 | +use React\EventLoop\LoopInterface; |
| 7 | +use React\EventLoop\Timer\Timer; |
| 8 | +use Rx\Disposable\CallbackDisposable; |
| 9 | +use Rx\ObserverInterface; |
| 10 | +use Rx\Subject\Subject; |
| 11 | + |
| 12 | +class ProcessSubject extends Subject |
| 13 | +{ |
| 14 | + private $process; |
| 15 | + private $loop; |
| 16 | + private $errorObserver; |
| 17 | + |
| 18 | + public function __construct($cmd, ObserverInterface $errorObserver = null, $cwd = null, array $env = null, array $options = [], LoopInterface $loop = null) |
| 19 | + { |
| 20 | + $this->process = $process = new Process($cmd, $cwd, $env, $options); |
| 21 | + $this->loop = $loop ?: \EventLoop\getLoop(); |
| 22 | + $this->errorObserver = $errorObserver ?: new Subject(); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @param $data |
| 27 | + */ |
| 28 | + public function onNext($data) |
| 29 | + { |
| 30 | + if ($this->process->stdin) { |
| 31 | + $this->process->stdin->write($data); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * @param ObserverInterface $observer |
| 37 | + * @param null $scheduler |
| 38 | + * @return CallbackDisposable |
| 39 | + */ |
| 40 | + public function subscribe(ObserverInterface $observer, $scheduler = null) |
| 41 | + { |
| 42 | + $this->loop->addTimer(0.001, function (Timer $timer) use ($observer) { |
| 43 | + |
| 44 | + try { |
| 45 | + $this->process->start($timer->getLoop()); |
| 46 | + |
| 47 | + $this->process->stdout->on('data', function ($output) use ($observer) { |
| 48 | + $observer->onNext($output); |
| 49 | + }); |
| 50 | + |
| 51 | + $this->process->stderr->on('data', function ($output) use ($observer) { |
| 52 | + if ($output) |
| 53 | + $this->errorObserver->onNext(new \Exception($output)); |
| 54 | + }); |
| 55 | + |
| 56 | + $this->process->stdout->on('close', function ($output) use ($observer) { |
| 57 | + $observer->onCompleted(); |
| 58 | + }); |
| 59 | + } catch (\Exception $e) { |
| 60 | + $observer->onError($e); |
| 61 | + } |
| 62 | + |
| 63 | + }); |
| 64 | + |
| 65 | + return new CallbackDisposable(function () { |
| 66 | + $this->process->terminate(); |
| 67 | + }); |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * @return Process |
| 72 | + */ |
| 73 | + public function getProcess() |
| 74 | + { |
| 75 | + return $this->process; |
| 76 | + } |
| 77 | +} |
0 commit comments