Completed
Push — master ( 756481...5cbf4f )
by Andrew
02:54
created

Emitter::createChain()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 10
cts 10
cp 1
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 3
1
<?php namespace Cairns\Radiate;
2
3
use Cairns\Radiate\Middleware\Middleware;
4
use Cairns\Radiate\Middleware\InvalidMiddlewareException;
5
6
final class Emitter
7
{
8
    /**
9
     * @var callable
10
     */
11
    private $pipeline;
12
13
    /**
14
     * @param Middleware[] $middleware
15
     */
16 2
    public function __construct($middleware)
17
    {
18 2
        $this->pipeline = $this->createChain($middleware);
19 1
    }
20
21
    /**
22
     * @param $event
23
     * @return mixed
24
     */
25 1
    public function emit($event)
26
    {
27 1
        $pipeline = $this->pipeline;
28
29 1
        return $pipeline($event);
30
    }
31
32
    /**
33
     * @param Middleware[] $middleware
34
     * @return callable
35
     */
36 2
    private function createChain($middleware)
37
    {
38
        $last = function () {
39
            // nothing
40 2
        };
41
42 2
        while ($link = array_pop($middleware)) {
43 2
            if (! $link instanceof Middleware) {
44 1
                throw new InvalidMiddlewareException('Shitballs!');
45
            }
46
47 1
            $last = function ($event) use ($link, $last) {
48 1
                return $link->execute($event, $last);
49 1
            };
50 1
        }
51
52 1
        return $last;
53
    }
54
}
55