CommandBus   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 56
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A handle() 0 9 2
A createExecutionChain() 0 18 3
1
<?php
2
3
namespace League\Tactician;
4
5
use League\Tactician\Exception\InvalidCommandException;
6
use League\Tactician\Exception\InvalidMiddlewareException;
7
8
/**
9
 * Receives a command and sends it through a chain of middleware for processing.
10
 *
11
 * @final
12
 */
13
class CommandBus
14
{
15
    /**
16
     * @var callable
17
     */
18
    private $middlewareChain;
19
20
    /**
21
     * @param Middleware[] $middleware
22
     */
23 8
    public function __construct(array $middleware)
24
    {
25 8
        $this->middlewareChain = $this->createExecutionChain($middleware);
26 7
    }
27
28
    /**
29
     * Executes the given command and optionally returns a value
30
     *
31
     * @param object $command
32
     *
33
     * @return mixed
34
     */
35 5
    public function handle($command)
36
    {
37 5
        if (!is_object($command)) {
38 1
            throw InvalidCommandException::forUnknownValue($command);
39
        }
40
41 4
        $middlewareChain = $this->middlewareChain;
42 4
        return $middlewareChain($command);
43
    }
44
45
    /**
46
     * @param Middleware[] $middlewareList
47
     *
48
     * @return callable
49
     */
50 8
    private function createExecutionChain($middlewareList)
51
    {
52
        $lastCallable = function () {
53
            // the final callable is a no-op
54 8
        };
55
56 8
        while ($middleware = array_pop($middlewareList)) {
57 6
            if (! $middleware instanceof Middleware) {
58 1
                throw InvalidMiddlewareException::forMiddleware($middleware);
59
            }
60
61 5
            $lastCallable = function ($command) use ($middleware, $lastCallable) {
62 3
                return $middleware->execute($command, $lastCallable);
63 5
            };
64
        }
65
66 7
        return $lastCallable;
67
    }
68
}
69