11
11
12
12
namespace Symfony \Component \Messenger \Transport \InMemory ;
13
13
14
+ use Psr \Clock \ClockInterface ;
14
15
use Symfony \Component \Messenger \Envelope ;
15
16
use Symfony \Component \Messenger \Exception \LogicException ;
17
+ use Symfony \Component \Messenger \Stamp \DelayStamp ;
16
18
use Symfony \Component \Messenger \Stamp \TransportMessageIdStamp ;
17
19
use Symfony \Component \Messenger \Transport \Serialization \SerializerInterface ;
18
20
use Symfony \Component \Messenger \Transport \TransportInterface ;
@@ -46,16 +48,25 @@ class InMemoryTransport implements TransportInterface, ResetInterface
46
48
private array $ queue = [];
47
49
48
50
private int $ nextId = 1 ;
49
- private ? SerializerInterface $ serializer ;
51
+ private array $ availableAt = [] ;
50
52
51
- public function __construct (SerializerInterface $ serializer = null )
52
- {
53
- $ this ->serializer = $ serializer ;
53
+ public function __construct (
54
+ private ?SerializerInterface $ serializer = null ,
55
+ private ?ClockInterface $ clock = null ,
56
+ ) {
54
57
}
55
58
56
59
public function get (): iterable
57
60
{
58
- return array_values ($ this ->decode ($ this ->queue ));
61
+ $ envelopes = [];
62
+ $ now = $ this ->clock ?->now() ?: new \DateTimeImmutable ();
63
+ foreach ($ this ->decode ($ this ->queue ) as $ id => $ envelope ) {
64
+ if (!isset ($ this ->availableAt [$ id ]) || $ now > $ this ->availableAt [$ id ]) {
65
+ $ envelopes [] = $ envelope ;
66
+ }
67
+ }
68
+
69
+ return $ envelopes ;
59
70
}
60
71
61
72
public function ack (Envelope $ envelope ): void
@@ -66,7 +77,7 @@ public function ack(Envelope $envelope): void
66
77
throw new LogicException ('No TransportMessageIdStamp found on the Envelope. ' );
67
78
}
68
79
69
- unset($ this ->queue [$ transportMessageIdStamp ->getId ()]);
80
+ unset($ this ->queue [$ id = $ transportMessageIdStamp ->getId ()], $ this -> availableAt [ $ id ]);
70
81
}
71
82
72
83
public function reject (Envelope $ envelope ): void
@@ -77,7 +88,7 @@ public function reject(Envelope $envelope): void
77
88
throw new LogicException ('No TransportMessageIdStamp found on the Envelope. ' );
78
89
}
79
90
80
- unset($ this ->queue [$ transportMessageIdStamp ->getId ()]);
91
+ unset($ this ->queue [$ id = $ transportMessageIdStamp ->getId ()], $ this -> availableAt [ $ id ]);
81
92
}
82
93
83
94
public function send (Envelope $ envelope ): Envelope
@@ -88,6 +99,12 @@ public function send(Envelope $envelope): Envelope
88
99
$ this ->sent [] = $ encodedEnvelope ;
89
100
$ this ->queue [$ id ] = $ encodedEnvelope ;
90
101
102
+ /** @var DelayStamp|null $delayStamp */
103
+ if ($ delayStamp = $ envelope ->last (DelayStamp::class)) {
104
+ $ now = $ this ->clock ?->now() ?: new \DateTimeImmutable ();
105
+ $ this ->availableAt [$ id ] = $ now ->modify (sprintf ('+%d seconds ' , $ delayStamp ->getDelay () / 1000 ));
106
+ }
107
+
91
108
return $ envelope ;
92
109
}
93
110
0 commit comments