| 1 | <?php |
||
| 8 | class RepeatHandler implements Middleware |
||
| 9 | { |
||
| 10 | /** @var Middleware|callable */ |
||
| 11 | private $handler; |
||
| 12 | |||
| 13 | public function __construct($handler) |
||
| 14 | { |
||
| 15 | $this->handler = $handler; |
||
| 16 | } |
||
| 17 | |||
| 18 | /** |
||
| 19 | * @inheritDoc |
||
| 20 | * @throws \Exception |
||
| 21 | */ |
||
| 22 | public function execute($command, callable $next) |
||
| 23 | { |
||
| 24 | $this->ensureCommandIsIterable($command); |
||
| 25 | $items = iterator_to_array($command, true); |
||
| 26 | $res = array_map(function ($item) { |
||
| 27 | return $this->handle($item); |
||
| 28 | }, $items); |
||
| 29 | |||
| 30 | return new ArrayCollection($res); |
||
| 31 | } |
||
| 32 | |||
| 33 | private function handle($item) |
||
| 34 | { |
||
| 35 | $handler = $this->handler; |
||
| 36 | if (is_callable($handler)) { |
||
| 37 | return $handler($item); |
||
| 38 | } elseif ($handler instanceof Middleware) { |
||
| 39 | return $handler->execute($item, fn ($command) => $command); |
||
|
|
|||
| 40 | } |
||
| 41 | throw new \RuntimeException(sprintf( |
||
| 42 | '%s expects handler to be closure or Middleware', |
||
| 43 | self::class |
||
| 44 | )); |
||
| 45 | } |
||
| 46 | |||
| 47 | private function ensureCommandIsIterable($command): void |
||
| 48 | { |
||
| 49 | if (!$command instanceof \IteratorAggregate) { |
||
| 58 |