-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiddlewareSequence.php
103 lines (89 loc) · 2.55 KB
/
MiddlewareSequence.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* This file is part of the Vection-Framework project.
* Visit project at /~https://github.com/Vection-Framework/Vection
*
* (c) Vection-Framework <vection@appsdock.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Vection\Component\Messenger;
use Closure;
use Vection\Contracts\Messenger\MessageBusMiddlewareInterface;
use Vection\Contracts\Messenger\MessageInterface;
use Vection\Contracts\Messenger\MiddlewareSequenceInterface;
/**
* Class MiddlewareSequence
*
* @package Vection\Component\Messenger
*
* @author David Lung <vection@davidlung.de>
*/
class MiddlewareSequence implements MiddlewareSequenceInterface
{
/**
* This property contains all middleware objects
* that will be executed sequentially.
*
* @var MessageBusMiddlewareInterface[]
*/
protected array $middleware = [];
/**
* This property contains an closure that returns
* an middleware object on each call. It uses a generator
* inside to return always the next middleware.
*
* @var Closure
*/
protected Closure $sequence;
/**
* This property contains the middleware that is currently
* selected to handle the message.
*
* @var MessageBusMiddlewareInterface
*/
protected MessageBusMiddlewareInterface $currentMiddleware;
/**
* @param mixed[] $middleware
*/
public function __construct(array $middleware)
{
$this->middleware = $middleware;
// @var Generator $generator
$generator = (function(){
foreach ($this->middleware as $m) {
yield $m;
}
})();
$this->sequence = static function() use ($generator){
$current = $generator->current();
$generator->next();
return $current;
};
}
/**
* Returns the current middleware which handles the message.
*
* @return MessageBusMiddlewareInterface
*/
public function getCurrent(): MessageBusMiddlewareInterface
{
return $this->currentMiddleware;
}
/**
* @param MessageInterface $message
*
* @return MessageInterface
*/
public function next(MessageInterface $message): MessageInterface
{
$middleware = ($this->sequence)();
if ($middleware !== null) {
$this->currentMiddleware = $middleware;
return $middleware->handle($message, $this);
}
return $message;
}
}