-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommandBus.php
60 lines (52 loc) · 1.53 KB
/
CommandBus.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace SmoothPhp\CommandBus;
use SmoothPhp\CommandBus\Exception\InvalidMiddlewareException;
use SmoothPhp\Contracts\CommandBus\Command;
use SmoothPhp\Contracts\CommandBus\CommandBusMiddleware;
/**
* Class CommandBus
* @package SmoothPhp\CommandBus
* @author Simon Bennett <[email protected]>
*/
final class CommandBus implements \SmoothPhp\Contracts\CommandBus\CommandBus
{
/**
* @var callable
*/
private $middlewareChain;
/**
* CommandBus constructor.
* @param CommandBusMiddleware[] $middleware
*/
public function __construct(array $middleware)
{
$this->middlewareChain = $this->generateMiddlewareCallChain($middleware);
}
/**
* @param Command $command
*/
public function execute(Command $command)
{
$middlewareChain = $this->middlewareChain;
return $middlewareChain($command);
}
/**
* @param $middleware
* @return \Closure
*/
private function generateMiddlewareCallChain($middlewareList)
{
$lastCallable = function () {
// the final callable does not run
};
while ($middleware = array_pop($middlewareList)) {
if (!$middleware instanceof CommandBusMiddleware) {
throw InvalidMiddlewareException::forMiddleware($middleware);
}
$lastCallable = function ($command) use ($middleware, $lastCallable) {
return $middleware->execute($command, $lastCallable);
};
}
return $lastCallable;
}
}