Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5c1f3a2

Browse files
committed
[Messenger] Stop worker when it should stop
1 parent aeba22c commit 5c1f3a2

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Symfony/Component/Messenger/Tests/WorkerTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;
2828
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
2929
use Symfony\Component\Messenger\Worker;
30+
use Symfony\Component\Messenger\Worker\StopWhenMessageCountIsExceededWorker;
3031
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
3132

3233
/**
@@ -361,6 +362,30 @@ public function testWorkerWithMultipleReceivers()
361362
// make sure they were processed in the correct order
362363
$this->assertSame([$envelope1, $envelope2, $envelope3, $envelope4, $envelope5, $envelope6], $processedEnvelopes);
363364
}
365+
366+
public function testWorkerWithDecorator()
367+
{
368+
$envelope1 = new Envelope(new DummyMessage('message1'));
369+
$envelope2 = new Envelope(new DummyMessage('message2'));
370+
$envelope3 = new Envelope(new DummyMessage('message3'));
371+
372+
$receiver = new DummyReceiver([
373+
[$envelope1, $envelope2, $envelope3],
374+
]);
375+
376+
$bus = $this->getMockBuilder(MessageBusInterface::class)->getMock();
377+
378+
$worker = new Worker([$receiver], $bus);
379+
$workerWithDecorator = new StopWhenMessageCountIsExceededWorker($worker, 2);
380+
$processedEnvelopes = [];
381+
$workerWithDecorator->run([], function (?Envelope $envelope) use ($worker, &$processedEnvelopes) {
382+
if (null !== $envelope) {
383+
$processedEnvelopes[] = $envelope;
384+
}
385+
});
386+
387+
$this->assertSame([$envelope1, $envelope2], $processedEnvelopes);
388+
}
364389
}
365390

366391
class DummyReceiver implements ReceiverInterface

src/Symfony/Component/Messenger/Worker.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ public function run(array $options = [], callable $onHandledCallback = null): vo
9292

9393
$this->handleMessage($envelope, $receiver, $transportName, $this->retryStrategies[$transportName] ?? null);
9494
$onHandled($envelope);
95+
96+
if ($this->shouldStop) {
97+
break 2;
98+
}
9599
}
96100

97101
// after handling a single receiver, quit and start the loop again

0 commit comments

Comments
 (0)