Completed
Push — master ( 882cbc...a9ee6a )
by
unknown
15:23
created

src/Endpoint/Middleware/RepeatHandler.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace hiapi\Core\Endpoint\Middleware;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use League\Tactician\Middleware;
7
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);
0 ignored issues
show
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_DOUBLE_ARROW, expecting ',' or ')'
Loading history...
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) {
50
            throw new \RuntimeException(sprintf(
51
                '%s expects command to be iterable, %s provided instead',
52
                self::class,
53
                get_class($command)
54
            ));
55
        }
56
    }
57
}
58