CommandBus::createExecutionChain()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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