Completed
Push — master ( 9a342a...a162ae )
by Andrii
13:06
created

RepeatHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 41
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A execute() 0 13 1
A ensureCommandIsIterable() 0 10 2
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
    /**
11
     * @var callable
12
     */
13
    private $handler;
14
15
    public function __construct(callable $handler)
16
    {
17
        $this->handler = $handler;
18
    }
19
20
    /**
21
     * @inheritDoc
22
     * @throws \Exception
23
     */
24
    public function execute($command, callable $next)
25
    {
26
        $this->ensureCommandIsIterable($command);
27
28
        $handler = $this->handler;
29
        $items = iterator_to_array($command, true);
30
31
        return new ArrayCollection(
32
            array_map(static function ($item) use ($handler) {
33
                return $handler($item);
34
            }, $items)
35
        );
36
    }
37
38
    private function ensureCommandIsIterable($command): void
39
    {
40
        if (!$command instanceof \IteratorAggregate) {
41
            throw new \RuntimeException(sprintf(
42
                '%s expects command to be iterable, %s provided instead',
43
                self::class,
44
                get_class($command)
45
            ));
46
        }
47
    }
48
}
49