CommandBus::handle()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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