|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Rx\Operator; |
| 4 | + |
| 5 | +use Rx\ObservableInterface; |
| 6 | +use Rx\Observer\CallbackObserver; |
| 7 | +use Rx\ObserverInterface; |
| 8 | +use Rx\SchedulerInterface; |
| 9 | + |
| 10 | +class MinOperator implements OperatorInterface |
| 11 | +{ |
| 12 | + /** @var callable|null */ |
| 13 | + private $comparer; |
| 14 | + |
| 15 | + /** |
| 16 | + * MinOperator constructor. |
| 17 | + * @param $comparer callable |
| 18 | + */ |
| 19 | + public function __construct(callable $comparer = null) |
| 20 | + { |
| 21 | + if ($comparer === null) { |
| 22 | + $comparer = function ($x, $y) { |
| 23 | + return $x > $y ? 1 : ($x < $y ? -1 : 0); |
| 24 | + }; |
| 25 | + } |
| 26 | + |
| 27 | + $this->comparer = $comparer; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * @inheritDoc |
| 32 | + */ |
| 33 | + public function __invoke( |
| 34 | + ObservableInterface $observable, |
| 35 | + ObserverInterface $observer, |
| 36 | + SchedulerInterface $scheduler = null |
| 37 | + ) { |
| 38 | + $previousMin = null; |
| 39 | + $comparing = false; |
| 40 | + |
| 41 | + return $observable->subscribe(new CallbackObserver( |
| 42 | + function ($x) use (&$comparing, &$previousMin, $observer) { |
| 43 | + if (!$comparing) { |
| 44 | + $comparing = true; |
| 45 | + $previousMin = $x; |
| 46 | + |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + try { |
| 51 | + $result = call_user_func($this->comparer, $x, $previousMin); |
| 52 | + if ($result < 0) { |
| 53 | + $previousMin = $x; |
| 54 | + } |
| 55 | + } catch (\Exception $e) { |
| 56 | + $observer->onError($e); |
| 57 | + } |
| 58 | + }, |
| 59 | + [$observer, 'onError'], |
| 60 | + function () use (&$comparing, &$previousMin, $observer) { |
| 61 | + if ($comparing) { |
| 62 | + $observer->onNext($previousMin); |
| 63 | + $observer->onCompleted(); |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + $observer->onError(new \Exception("Empty")); |
| 68 | + } |
| 69 | + ), $scheduler); |
| 70 | + } |
| 71 | +} |
0 commit comments