CommandBus   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 7
dl 0
loc 32
ccs 10
cts 10
cp 1
rs 10
c 5
b 1
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A handle() 0 3 1
A createExecutionChain() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Tactician;
6
7
use Closure;
8
9
use function array_pop;
10
11
/**
12
 * Receives a command and sends it through a chain of middleware for processing.
13
 */
14
final class CommandBus
15
{
16
    /** @var Closure(object $command):mixed */
17
    private Closure $middlewareChain;
18
19 3
    public function __construct(Middleware ...$middleware)
20
    {
21 3
        $this->middlewareChain = $this->createExecutionChain($middleware);
22 3
    }
23
24
    /**
25
     * Executes the given command and optionally returns a value
26
     *
27
     * @return mixed
28
     */
29 3
    public function handle(object $command)
30
    {
31 3
        return ($this->middlewareChain)($command);
32
    }
33
34
    /**
35
     * @param Middleware[] $middlewareList
36
     */
37 3
    private function createExecutionChain(array $middlewareList): Closure
38
    {
39 3
        $lastCallable = static fn () => null;
40
41 3
        while ($middleware = array_pop($middlewareList)) {
42 2
            $lastCallable = static fn (object $command) => $middleware->execute($command, $lastCallable);
43
        }
44
45 3
        return $lastCallable;
46
    }
47
}
48