diff --git a/UPGRADE-4.4.md b/UPGRADE-4.4.md
index e05d5772fb956..5723a27aab7ac 100644
--- a/UPGRADE-4.4.md
+++ b/UPGRADE-4.4.md
@@ -96,6 +96,11 @@ FrameworkBundle
* Not tagging service route loaders with `routing.route_loader` has been deprecated.
* Overriding the methods `KernelTestCase::tearDown()` and `WebTestCase::tearDown()` without the `void` return-type is deprecated.
* Marked the `RouterDataCollector` class as `@final`.
+ * [BC BREAK] If you defined more than one bus, you must set the "bus" config option on the transport.
+ Messages received from this transport will be dispatched to this bus automatically. This replaces the
+ `--bus` option of `messenger:consume` command and the `BusNameStamp`.
+ * [BC Break] Removed `messenger.middleware.add_bus_name_stamp_middleware` service
+ * [BC Break] Removed `messenger.middleware.failed_message_processing_middleware` service
HttpClient
----------
@@ -179,6 +184,11 @@ Messenger
* [BC BREAK] Removed `StopWhenMessageCountIsExceededWorker` in favor of `StopWorkerOnMessageLimitListener`.
* [BC BREAK] Removed `StopWhenTimeLimitIsReachedWorker` in favor of `StopWorkerOnTimeLimitListener`.
* [BC BREAK] Removed `StopWhenRestartSignalIsReceived` in favor of `StopWorkerOnRestartSignalListener`.
+ * Deprecated `BusNameStamp`.
+ * [BC BREAK] Removed `AddBusNameStampMiddleware`.
+ * [BC BREAK] Removed `FailedMessageProcessingMiddleware`.
+ * [BC BREAK] Removed `--bus` option of `messenger:consume` command in favor of the "bus" config on the transport.
+ * [BC BREAK] Removed `$fallbackBus` argument from `RoutableMessageBus::__construct`.
* Marked the `MessengerDataCollector` class as `@final`.
Mime
diff --git a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
index 60e1e319f719d..4d72463504dd8 100644
--- a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
+++ b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
@@ -17,7 +17,13 @@ CHANGELOG
* Overriding the methods `KernelTestCase::tearDown()` and `WebTestCase::tearDown()` without the `void` return-type is deprecated.
* Added new `error_controller` configuration to handle system exceptions
* Added sort option for `translation:update` command.
+ * The `messenger.default_bus` config option is optional now even when having more than one bus to prevent unwanted autowiring.
+ * [BC BREAK] If you defined more than one bus, you must set the "bus" config option on the transport.
+ Messages received from this transport will be dispatched to this bus automatically. This replaces the
+ `--bus` option of `messenger:consume` command and the `BusNameStamp`.
* [BC Break] The `framework.messenger.routing.senders` config key is not deep merged anymore.
+ * [BC Break] Removed `messenger.middleware.add_bus_name_stamp_middleware` service
+ * [BC Break] Removed `messenger.middleware.failed_message_processing_middleware` service
* Added `secrets:*` commands and `%env(secret:...)%` processor to deal with secrets seamlessly.
* Made `framework.session.handler_id` accept a DSN
* Marked the `RouterDataCollector` class as `@final`.
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
index 405aff41d7fed..83f2626df1eaa 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
@@ -1168,10 +1168,6 @@ private function addMessengerSection(ArrayNodeDefinition $rootNode)
->{!class_exists(FullStack::class) && interface_exists(MessageBusInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->fixXmlConfig('transport')
->fixXmlConfig('bus', 'buses')
- ->validate()
- ->ifTrue(function ($v) { return isset($v['buses']) && \count($v['buses']) > 1 && null === $v['default_bus']; })
- ->thenInvalid('You must specify the "default_bus" if you define more than one bus.')
- ->end()
->children()
->arrayNode('routing')
->normalizeKeys(false)
@@ -1247,7 +1243,14 @@ function ($a) {
->fixXmlConfig('option')
->children()
->scalarNode('dsn')->end()
- ->scalarNode('serializer')->defaultNull()->info('Service id of a custom serializer to use.')->end()
+ ->scalarNode('serializer')
+ ->defaultNull()
+ ->info('Service id of a custom serializer to use.')
+ ->end()
+ ->scalarNode('bus')
+ ->defaultNull()
+ ->info('Bus name to dispatch received messages to. This only needs to be set if you have more than one bus.')
+ ->end()
->arrayNode('options')
->normalizeKeys(false)
->defaultValue([])
@@ -1280,7 +1283,10 @@ function ($a) {
->defaultNull()
->info('Transport name to send failed messages to (after all retries have failed).')
->end()
- ->scalarNode('default_bus')->defaultNull()->end()
+ ->scalarNode('default_bus')
+ ->defaultNull()
+ ->info('Bus name that will be used for autowiring MessageBusInterface. When there is only a single bus this happens automatically. With multiple buses you can set this option or use named autowiring based on the bus name or explicit wiring.')
+ ->end()
->arrayNode('buses')
->defaultValue(['messenger.bus.default' => ['default_middleware' => true, 'middleware' => []]])
->normalizeKeys(false)
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
index 0d395d59c996e..794863a0d4c51 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
@@ -1696,10 +1696,8 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
$defaultMiddleware = [
'before' => [
- ['id' => 'add_bus_name_stamp_middleware'],
['id' => 'reject_redelivered_message_middleware'],
['id' => 'dispatch_after_current_bus'],
- ['id' => 'failed_message_processing_middleware'],
],
'after' => [
['id' => 'send_message'],
@@ -1716,9 +1714,6 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
unset($defaultMiddleware['after'][1]['arguments']);
}
- // argument to add_bus_name_stamp_middleware
- $defaultMiddleware['before'][0]['arguments'] = [$busId];
-
$middleware = array_merge($defaultMiddleware['before'], $middleware, $defaultMiddleware['after']);
}
@@ -1763,7 +1758,7 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
$transportDefinition = (new Definition(TransportInterface::class))
->setFactory([new Reference('messenger.transport_factory'), 'createTransport'])
->setArguments([$transport['dsn'], $transport['options'] + ['transport_name' => $name], new Reference($serializerId)])
- ->addTag('messenger.receiver', ['alias' => $name])
+ ->addTag('messenger.receiver', ['alias' => $name, 'bus' => $transport['bus']])
;
$container->setDefinition($transportId = 'messenger.transport.'.$name, $transportDefinition);
$senderAliases[$name] = $transportId;
@@ -1829,14 +1824,9 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
throw new LogicException(sprintf('Invalid Messenger configuration: the failure transport "%s" is not a valid transport or service id.', $config['failure_transport']));
}
+ $container->setParameter('messenger.failure_transport', $config['failure_transport']);
$container->getDefinition('messenger.failure.send_failed_message_to_failure_transport_listener')
->replaceArgument(0, $senderReferences[$config['failure_transport']]);
- $container->getDefinition('console.command.messenger_failed_messages_retry')
- ->replaceArgument(0, $config['failure_transport']);
- $container->getDefinition('console.command.messenger_failed_messages_show')
- ->replaceArgument(0, $config['failure_transport']);
- $container->getDefinition('console.command.messenger_failed_messages_remove')
- ->replaceArgument(0, $config['failure_transport']);
} else {
$container->removeDefinition('messenger.failure.send_failed_message_to_failure_transport_listener');
$container->removeDefinition('console.command.messenger_failed_messages_retry');
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml
index 73b9eff6fe426..5a58a84c87b06 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml
+++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml
@@ -86,7 +86,7 @@
-
+
@@ -115,7 +115,7 @@
-
+ %messenger.failure_transport%
@@ -125,14 +125,14 @@
-
+ %messenger.failure_transport%
-
+ %messenger.failure_transport%
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/messenger.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/messenger.xml
index 14117ee8e40a4..2b1f6a35425dd 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/messenger.xml
+++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/messenger.xml
@@ -40,8 +40,6 @@
-
-
@@ -50,8 +48,6 @@
-
-
@@ -132,7 +128,6 @@
-
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php
index f79897a6badd0..db2f69695114b 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php
@@ -250,27 +250,6 @@ public function provideValidLockConfigurationTests()
yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]];
}
- public function testItShowANiceMessageIfTwoMessengerBusesAreConfiguredButNoDefaultBus()
- {
- $expectedMessage = 'You must specify the "default_bus" if you define more than one bus.';
- $this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage($expectedMessage);
- $processor = new Processor();
- $configuration = new Configuration(true);
-
- $processor->processConfiguration($configuration, [
- 'framework' => [
- 'messenger' => [
- 'default_bus' => null,
- 'buses' => [
- 'first_bus' => [],
- 'second_bus' => [],
- ],
- ],
- ],
- ]);
- }
-
protected static function getBundleDefaultConfig()
{
return [
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php
index 1e97f61d7cbc9..29aef250932dc 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php
@@ -679,7 +679,7 @@ public function testMessengerTransports()
$container = $this->createContainerFromFile('messenger_transports');
$this->assertTrue($container->hasDefinition('messenger.transport.default'));
$this->assertTrue($container->getDefinition('messenger.transport.default')->hasTag('messenger.receiver'));
- $this->assertEquals([['alias' => 'default']], $container->getDefinition('messenger.transport.default')->getTag('messenger.receiver'));
+ $this->assertEquals([['alias' => 'default', 'bus' => null]], $container->getDefinition('messenger.transport.default')->getTag('messenger.receiver'));
$transportArguments = $container->getDefinition('messenger.transport.default')->getArguments();
$this->assertEquals(new Reference('messenger.default_serializer'), $transportArguments[2]);
@@ -737,20 +737,16 @@ public function testMessengerWithMultipleBuses()
$this->assertTrue($container->has('messenger.bus.commands'));
$this->assertSame([], $container->getDefinition('messenger.bus.commands')->getArgument(0));
$this->assertEquals([
- ['id' => 'add_bus_name_stamp_middleware', 'arguments' => ['messenger.bus.commands']],
['id' => 'reject_redelivered_message_middleware'],
['id' => 'dispatch_after_current_bus'],
- ['id' => 'failed_message_processing_middleware'],
['id' => 'send_message'],
['id' => 'handle_message'],
], $container->getParameter('messenger.bus.commands.middleware'));
$this->assertTrue($container->has('messenger.bus.events'));
$this->assertSame([], $container->getDefinition('messenger.bus.events')->getArgument(0));
$this->assertEquals([
- ['id' => 'add_bus_name_stamp_middleware', 'arguments' => ['messenger.bus.events']],
['id' => 'reject_redelivered_message_middleware'],
['id' => 'dispatch_after_current_bus'],
- ['id' => 'failed_message_processing_middleware'],
['id' => 'with_factory', 'arguments' => ['foo', true, ['bar' => 'baz']]],
['id' => 'send_message'],
['id' => 'handle_message'],
diff --git a/src/Symfony/Component/Messenger/CHANGELOG.md b/src/Symfony/Component/Messenger/CHANGELOG.md
index 7ae4a2b63c7c7..40d8fcdea7c47 100644
--- a/src/Symfony/Component/Messenger/CHANGELOG.md
+++ b/src/Symfony/Component/Messenger/CHANGELOG.md
@@ -21,6 +21,11 @@ CHANGELOG
* [BC BREAK] Removed `StopWhenMessageCountIsExceededWorker` in favor of `StopWorkerOnMessageLimitListener`.
* [BC BREAK] Removed `StopWhenTimeLimitIsReachedWorker` in favor of `StopWorkerOnTimeLimitListener`.
* [BC BREAK] Removed `StopWhenRestartSignalIsReceived` in favor of `StopWorkerOnRestartSignalListener`.
+ * Deprecated `BusNameStamp`.
+ * [BC BREAK] Removed `AddBusNameStampMiddleware`.
+ * [BC BREAK] Removed `FailedMessageProcessingMiddleware`.
+ * [BC BREAK] Removed `--bus` option of `messenger:consume` command in favor of the "bus" config on the transport.
+ * [BC BREAK] Removed `$fallbackBus` argument from `RoutableMessageBus::__construct`.
* The component is not marked as `@experimental` anymore.
* Marked the `MessengerDataCollector` class as `@final`.
* Added support for `DelayStamp` to the `redis` transport.
diff --git a/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php b/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php
index 2347ce3c8c8be..6303b60ed538f 100644
--- a/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php
+++ b/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php
@@ -42,18 +42,8 @@ class ConsumeMessagesCommand extends Command
private $receiverNames;
private $eventDispatcher;
- /**
- * @param RoutableMessageBus $routableBus
- */
- public function __construct($routableBus, ContainerInterface $receiverLocator, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null, array $receiverNames = [])
+ public function __construct(RoutableMessageBus $routableBus, ContainerInterface $receiverLocator, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null, array $receiverNames = [])
{
- if ($routableBus instanceof ContainerInterface) {
- @trigger_error(sprintf('Passing a "%s" instance as first argument to "%s()" is deprecated since Symfony 4.4, pass a "%s" instance instead.', ContainerInterface::class, __METHOD__, RoutableMessageBus::class), E_USER_DEPRECATED);
- $routableBus = new RoutableMessageBus($routableBus);
- } elseif (!$routableBus instanceof RoutableMessageBus) {
- throw new \TypeError(sprintf('The first argument must be an instance of "%s".', RoutableMessageBus::class));
- }
-
$this->routableBus = $routableBus;
$this->receiverLocator = $receiverLocator;
$this->logger = $logger;
@@ -77,7 +67,6 @@ protected function configure(): void
new InputOption('memory-limit', 'm', InputOption::VALUE_REQUIRED, 'The memory limit the worker can consume'),
new InputOption('time-limit', 't', InputOption::VALUE_REQUIRED, 'The time limit in seconds the worker can run'),
new InputOption('sleep', null, InputOption::VALUE_REQUIRED, 'Seconds to sleep before asking for new messages after no messages were found', 1),
- new InputOption('bus', 'b', InputOption::VALUE_REQUIRED, 'Name of the bus to which received messages should be dispatched (if not passed, bus is determined automatically)'),
])
->setDescription('Consumes messages')
->setHelp(<<<'EOF'
@@ -100,12 +89,6 @@ protected function configure(): void
Use the --time-limit option to stop the worker when the given time limit (in seconds) is reached:
php %command.full_name% --time-limit=3600
-
-Use the --bus option to specify the message bus to dispatch received messages
-to instead of trying to determine it automatically. This is required if the
-messages didn't originate from Messenger:
-
- php %command.full_name% --bus=event_bus
EOF
)
;
@@ -195,9 +178,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$io->comment('Re-run the command with a -vv option to see logs about consumed messages.');
}
- $bus = $input->getOption('bus') ? $this->routableBus->getMessageBus($input->getOption('bus')) : $this->routableBus;
-
- $worker = new Worker($receivers, $bus, $this->eventDispatcher, $this->logger);
+ $worker = new Worker($receivers, $this->routableBus, $this->eventDispatcher, $this->logger);
$worker->run([
'sleep' => $input->getOption('sleep') * 1000000,
]);
diff --git a/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php b/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php
index 696e77f7f1949..9ae51c152241b 100644
--- a/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php
+++ b/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php
@@ -23,7 +23,7 @@
use Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent;
use Symfony\Component\Messenger\EventListener\StopWorkerOnMessageLimitListener;
use Symfony\Component\Messenger\Exception\LogicException;
-use Symfony\Component\Messenger\MessageBusInterface;
+use Symfony\Component\Messenger\RoutableMessageBus;
use Symfony\Component\Messenger\Transport\Receiver\ListableReceiverInterface;
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
use Symfony\Component\Messenger\Transport\Receiver\SingleMessageReceiver;
@@ -40,7 +40,7 @@ class FailedMessagesRetryCommand extends AbstractFailedMessagesCommand
private $messageBus;
private $logger;
- public function __construct(string $receiverName, ReceiverInterface $receiver, MessageBusInterface $messageBus, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null)
+ public function __construct(string $receiverName, ReceiverInterface $receiver, RoutableMessageBus $messageBus, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null)
{
$this->eventDispatcher = $eventDispatcher;
$this->messageBus = $messageBus;
diff --git a/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php b/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php
index 4ab31e840444f..a18017f3f0b5d 100644
--- a/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php
+++ b/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php
@@ -238,6 +238,7 @@ private function guessHandledClasses(\ReflectionClass $handlerClass, string $ser
private function registerReceivers(ContainerBuilder $container, array $busIds)
{
$receiverMapping = [];
+ $receiverToBusMapping = [];
foreach ($container->findTaggedServiceIds($this->receiverTag) as $id => $tags) {
$receiverClass = $container->findDefinition($id)->getClass();
@@ -247,9 +248,38 @@ private function registerReceivers(ContainerBuilder $container, array $busIds)
$receiverMapping[$id] = new Reference($id);
+ $namesForReceiver = [$id];
+ $busIdForReceiver = null;
foreach ($tags as $tag) {
if (isset($tag['alias'])) {
$receiverMapping[$tag['alias']] = $receiverMapping[$id];
+ $namesForReceiver[] = $tag['alias'];
+ }
+ if (isset($tag['bus'])) {
+ $busIdForReceiver = $tag['bus'];
+ }
+ }
+
+ // for the failure transport the bus does not need to be set as the bus is determined based on the original receiver per message
+ // if the bus is set anyway (or there is only one bus), we can use it as a fallback in case the original receiver does not exist anymore (e.g. was renamed)
+ $isFailureTransport = false;
+ if ($container->hasParameter('messenger.failure_transport')) {
+ $isFailureTransport = \in_array($container->getParameter('messenger.failure_transport'), $namesForReceiver, true);
+ }
+
+ if (\count($busIds) > 1 && null === $busIdForReceiver && !$isFailureTransport) {
+ throw new RuntimeException(sprintf('Invalid receiver "%s": As you have more than one bus, you need to set the "bus" option on the transport configuration or use such a tag attribute on the service definition.', $id));
+ }
+ if (null !== $busIdForReceiver && !\in_array($busIdForReceiver, $busIds, true)) {
+ throw new RuntimeException(sprintf('Invalid receiver "%s": Configured bus "%s" does not exist (known ones are: %s).', $id, $busIdForReceiver, implode(', ', $busIds)));
+ }
+ if (1 === \count($busIds) && null === $busIdForReceiver) {
+ $busIdForReceiver = $busIds[0];
+ }
+ if (null !== $busIdForReceiver) {
+ $busRef = new Reference($busIdForReceiver);
+ foreach ($namesForReceiver as $receiverName) {
+ $receiverToBusMapping[$receiverName] = $busRef;
}
}
}
@@ -259,24 +289,14 @@ private function registerReceivers(ContainerBuilder $container, array $busIds)
$receiverNames[(string) $reference] = $name;
}
- $buses = [];
- foreach ($busIds as $busId) {
- $buses[$busId] = new Reference($busId);
- }
-
- if ($hasRoutableMessageBus = $container->hasDefinition('messenger.routable_message_bus')) {
+ if ($container->hasDefinition('messenger.routable_message_bus')) {
$container->getDefinition('messenger.routable_message_bus')
- ->replaceArgument(0, ServiceLocatorTagPass::register($container, $buses));
+ ->replaceArgument(0, ServiceLocatorTagPass::register($container, $receiverToBusMapping));
}
if ($container->hasDefinition('console.command.messenger_consume_messages')) {
- $consumeCommandDefinition = $container->getDefinition('console.command.messenger_consume_messages');
-
- if ($hasRoutableMessageBus) {
- $consumeCommandDefinition->replaceArgument(0, new Reference('messenger.routable_message_bus'));
- }
-
- $consumeCommandDefinition->replaceArgument(4, array_values($receiverNames));
+ $container->getDefinition('console.command.messenger_consume_messages')
+ ->replaceArgument(4, array_values($receiverNames));
}
if ($container->hasDefinition('console.command.messenger_setup_transports')) {
@@ -293,8 +313,8 @@ private function registerReceivers(ContainerBuilder $container, array $busIds)
];
foreach ($failedCommandIds as $failedCommandId) {
if ($container->hasDefinition($failedCommandId)) {
- $definition = $container->getDefinition($failedCommandId);
- $definition->replaceArgument(1, $receiverMapping[$definition->getArgument(0)]);
+ $container->getDefinition($failedCommandId)
+ ->replaceArgument(1, $receiverMapping[$container->getParameter('messenger.failure_transport')]);
}
}
}
diff --git a/src/Symfony/Component/Messenger/Middleware/AddBusNameStampMiddleware.php b/src/Symfony/Component/Messenger/Middleware/AddBusNameStampMiddleware.php
deleted file mode 100644
index 925fd5f7fd2de..0000000000000
--- a/src/Symfony/Component/Messenger/Middleware/AddBusNameStampMiddleware.php
+++ /dev/null
@@ -1,39 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Component\Messenger\Middleware;
-
-use Symfony\Component\Messenger\Envelope;
-use Symfony\Component\Messenger\Stamp\BusNameStamp;
-
-/**
- * Adds the BusNameStamp to the bus.
- *
- * @author Ryan Weaver
- */
-class AddBusNameStampMiddleware implements MiddlewareInterface
-{
- private $busName;
-
- public function __construct(string $busName)
- {
- $this->busName = $busName;
- }
-
- public function handle(Envelope $envelope, StackInterface $stack): Envelope
- {
- if (null === $envelope->last(BusNameStamp::class)) {
- $envelope = $envelope->with(new BusNameStamp($this->busName));
- }
-
- return $stack->next()->handle($envelope, $stack);
- }
-}
diff --git a/src/Symfony/Component/Messenger/Middleware/FailedMessageProcessingMiddleware.php b/src/Symfony/Component/Messenger/Middleware/FailedMessageProcessingMiddleware.php
deleted file mode 100644
index 6e40d1127d65a..0000000000000
--- a/src/Symfony/Component/Messenger/Middleware/FailedMessageProcessingMiddleware.php
+++ /dev/null
@@ -1,36 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Component\Messenger\Middleware;
-
-use Symfony\Component\Messenger\Envelope;
-use Symfony\Component\Messenger\Stamp\ReceivedStamp;
-use Symfony\Component\Messenger\Stamp\SentToFailureTransportStamp;
-
-/**
- * @author Ryan Weaver
- */
-class FailedMessageProcessingMiddleware implements MiddlewareInterface
-{
- public function handle(Envelope $envelope, StackInterface $stack): Envelope
- {
- // look for "received" messages decorated with the SentToFailureTransportStamp
- /** @var SentToFailureTransportStamp|null $sentToFailureStamp */
- $sentToFailureStamp = $envelope->last(SentToFailureTransportStamp::class);
- if (null !== $sentToFailureStamp && null !== $envelope->last(ReceivedStamp::class)) {
- // mark the message as "received" from the original transport
- // this guarantees the same behavior as when originally received
- $envelope = $envelope->with(new ReceivedStamp($sentToFailureStamp->getOriginalReceiverName()));
- }
-
- return $stack->next()->handle($envelope, $stack);
- }
-}
diff --git a/src/Symfony/Component/Messenger/RoutableMessageBus.php b/src/Symfony/Component/Messenger/RoutableMessageBus.php
index 6fde1687b5c52..7825f9baabe51 100644
--- a/src/Symfony/Component/Messenger/RoutableMessageBus.php
+++ b/src/Symfony/Component/Messenger/RoutableMessageBus.php
@@ -13,25 +13,25 @@
use Psr\Container\ContainerInterface;
use Symfony\Component\Messenger\Exception\InvalidArgumentException;
-use Symfony\Component\Messenger\Stamp\BusNameStamp;
+use Symfony\Component\Messenger\Stamp\ReceivedStamp;
+use Symfony\Component\Messenger\Stamp\SentToFailureTransportStamp;
/**
- * Bus of buses that is routable using a BusNameStamp.
+ * Bus of buses that is routable by reading the ReceivedStamp and locating the bus for the given transport name.
*
* This is useful when passed to Worker: messages received
* from the transport can be sent to the correct bus.
*
* @author Ryan Weaver
+ * @author Tobias Schultze
*/
class RoutableMessageBus implements MessageBusInterface
{
private $busLocator;
- private $fallbackBus;
- public function __construct(ContainerInterface $busLocator, MessageBusInterface $fallbackBus = null)
+ public function __construct(ContainerInterface $busLocator)
{
$this->busLocator = $busLocator;
- $this->fallbackBus = $fallbackBus;
}
public function dispatch($envelope, array $stamps = []): Envelope
@@ -40,29 +40,39 @@ public function dispatch($envelope, array $stamps = []): Envelope
throw new InvalidArgumentException('Messages passed to RoutableMessageBus::dispatch() must be inside an Envelope');
}
- /** @var BusNameStamp|null $busNameStamp */
- $busNameStamp = $envelope->last(BusNameStamp::class);
+ /** @var ReceivedStamp|null $receivedStamp */
+ $receivedStamp = $envelope->last(ReceivedStamp::class);
- if (null === $busNameStamp) {
- if (null === $this->fallbackBus) {
- throw new InvalidArgumentException(sprintf('Envelope is missing a BusNameStamp and no fallback message bus is configured on RoutableMessageBus.'));
+ if (null === $receivedStamp) {
+ // The RoutableMessageBus is only used in Worker context where the ReceivedStamp is added. So this should not happen.
+ throw new InvalidArgumentException('Envelope is missing a ReceivedStamp.');
+ }
+
+ $transportName = $receivedStamp->getTransportName();
+
+ /** @var SentToFailureTransportStamp|null $sentToFailureStamp */
+ $sentToFailureStamp = $envelope->last(SentToFailureTransportStamp::class);
+ if (null !== $sentToFailureStamp) {
+ // if the message was received from the failure transport, mark the message as received from the original transport and use the bus based on it
+ // this guarantees the same behavior when consuming from the failure transport (directly or via messenger:failed:retry) as when originally received
+ $originalReceiver = $sentToFailureStamp->getOriginalReceiverName();
+ // in case the original receiver does not exist anymore, use the bus configured for failure transport
+ if ($this->busLocator->has($originalReceiver)) {
+ $transportName = $originalReceiver;
}
- return $this->fallbackBus->dispatch($envelope, $stamps);
+ $envelope = $envelope->with(new ReceivedStamp($originalReceiver));
}
- return $this->getMessageBus($busNameStamp->getBusName())->dispatch($envelope, $stamps);
+ return $this->getMessageBusForTransport($transportName)->dispatch($envelope, $stamps);
}
- /**
- * @internal
- */
- public function getMessageBus(string $busName): MessageBusInterface
+ private function getMessageBusForTransport(string $transportName): MessageBusInterface
{
- if (!$this->busLocator->has($busName)) {
- throw new InvalidArgumentException(sprintf('Bus named "%s" does not exist.', $busName));
+ if (!$this->busLocator->has($transportName)) {
+ throw new InvalidArgumentException(sprintf('Could not find a bus for transport "%s".', $transportName));
}
- return $this->busLocator->get($busName);
+ return $this->busLocator->get($transportName);
}
}
diff --git a/src/Symfony/Component/Messenger/Stamp/BusNameStamp.php b/src/Symfony/Component/Messenger/Stamp/BusNameStamp.php
index e9765c0c74da8..921db07cc5723 100644
--- a/src/Symfony/Component/Messenger/Stamp/BusNameStamp.php
+++ b/src/Symfony/Component/Messenger/Stamp/BusNameStamp.php
@@ -11,9 +11,13 @@
namespace Symfony\Component\Messenger\Stamp;
+@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.4.', BusNameStamp::class), E_USER_DEPRECATED);
+
/**
* Stamp used to identify which bus it was passed to.
*
+ * @deprecated since Symfony 4.4
+ *
* @author Ryan Weaver
*/
final class BusNameStamp implements StampInterface
diff --git a/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php
index 7b56e74fb2984..de8f351e25b7e 100644
--- a/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php
+++ b/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php
@@ -22,7 +22,6 @@
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\RoutableMessageBus;
-use Symfony\Component\Messenger\Stamp\BusNameStamp;
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
class ConsumeMessagesCommandTest extends TestCase
@@ -36,38 +35,6 @@ public function testConfigurationWithDefaultReceiver()
}
public function testBasicRun()
- {
- $envelope = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
-
- $receiver = $this->createMock(ReceiverInterface::class);
- $receiver->expects($this->once())->method('get')->willReturn([$envelope]);
-
- $receiverLocator = $this->createMock(ContainerInterface::class);
- $receiverLocator->expects($this->once())->method('has')->with('dummy-receiver')->willReturn(true);
- $receiverLocator->expects($this->once())->method('get')->with('dummy-receiver')->willReturn($receiver);
-
- $bus = $this->createMock(MessageBusInterface::class);
- $bus->expects($this->once())->method('dispatch');
-
- $busLocator = $this->createMock(ContainerInterface::class);
- $busLocator->expects($this->once())->method('has')->with('dummy-bus')->willReturn(true);
- $busLocator->expects($this->once())->method('get')->with('dummy-bus')->willReturn($bus);
-
- $command = new ConsumeMessagesCommand(new RoutableMessageBus($busLocator), $receiverLocator, new EventDispatcher());
-
- $application = new Application();
- $application->add($command);
- $tester = new CommandTester($application->get('messenger:consume'));
- $tester->execute([
- 'receivers' => ['dummy-receiver'],
- '--limit' => 1,
- ]);
-
- $this->assertSame(0, $tester->getStatusCode());
- $this->assertStringContainsString('[OK] Consuming messages from transports "dummy-receiver"', $tester->getDisplay());
- }
-
- public function testRunWithBusOption()
{
$envelope = new Envelope(new \stdClass());
@@ -82,8 +49,8 @@ public function testRunWithBusOption()
$bus->expects($this->once())->method('dispatch');
$busLocator = $this->createMock(ContainerInterface::class);
- $busLocator->expects($this->once())->method('has')->with('dummy-bus')->willReturn(true);
- $busLocator->expects($this->once())->method('get')->with('dummy-bus')->willReturn($bus);
+ $busLocator->expects($this->once())->method('has')->with('dummy-receiver')->willReturn(true);
+ $busLocator->expects($this->once())->method('get')->with('dummy-receiver')->willReturn($bus);
$command = new ConsumeMessagesCommand(new RoutableMessageBus($busLocator), $receiverLocator, new EventDispatcher());
@@ -92,80 +59,6 @@ public function testRunWithBusOption()
$tester = new CommandTester($application->get('messenger:consume'));
$tester->execute([
'receivers' => ['dummy-receiver'],
- '--bus' => 'dummy-bus',
- '--limit' => 1,
- ]);
-
- $this->assertSame(0, $tester->getStatusCode());
- $this->assertStringContainsString('[OK] Consuming messages from transports "dummy-receiver"', $tester->getDisplay());
- }
-
- /**
- * @group legacy
- * @expectedDeprecation Passing a "Psr\Container\ContainerInterface" instance as first argument to "Symfony\Component\Messenger\Command\ConsumeMessagesCommand::__construct()" is deprecated since Symfony 4.4, pass a "Symfony\Component\Messenger\RoutableMessageBus" instance instead.
- */
- public function testBasicRunWithBusLocator()
- {
- $envelope = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]);
-
- $receiver = $this->createMock(ReceiverInterface::class);
- $receiver->expects($this->once())->method('get')->willReturn([$envelope]);
-
- $receiverLocator = $this->createMock(ContainerInterface::class);
- $receiverLocator->expects($this->once())->method('has')->with('dummy-receiver')->willReturn(true);
- $receiverLocator->expects($this->once())->method('get')->with('dummy-receiver')->willReturn($receiver);
-
- $bus = $this->createMock(MessageBusInterface::class);
- $bus->expects($this->once())->method('dispatch');
-
- $busLocator = $this->createMock(ContainerInterface::class);
- $busLocator->expects($this->once())->method('has')->with('dummy-bus')->willReturn(true);
- $busLocator->expects($this->once())->method('get')->with('dummy-bus')->willReturn($bus);
-
- $command = new ConsumeMessagesCommand($busLocator, $receiverLocator, new EventDispatcher());
-
- $application = new Application();
- $application->add($command);
- $tester = new CommandTester($application->get('messenger:consume'));
- $tester->execute([
- 'receivers' => ['dummy-receiver'],
- '--limit' => 1,
- ]);
-
- $this->assertSame(0, $tester->getStatusCode());
- $this->assertStringContainsString('[OK] Consuming messages from transports "dummy-receiver"', $tester->getDisplay());
- }
-
- /**
- * @group legacy
- * @expectedDeprecation Passing a "Psr\Container\ContainerInterface" instance as first argument to "Symfony\Component\Messenger\Command\ConsumeMessagesCommand::__construct()" is deprecated since Symfony 4.4, pass a "Symfony\Component\Messenger\RoutableMessageBus" instance instead.
- */
- public function testRunWithBusOptionAndBusLocator()
- {
- $envelope = new Envelope(new \stdClass());
-
- $receiver = $this->createMock(ReceiverInterface::class);
- $receiver->expects($this->once())->method('get')->willReturn([$envelope]);
-
- $receiverLocator = $this->createMock(ContainerInterface::class);
- $receiverLocator->expects($this->once())->method('has')->with('dummy-receiver')->willReturn(true);
- $receiverLocator->expects($this->once())->method('get')->with('dummy-receiver')->willReturn($receiver);
-
- $bus = $this->createMock(MessageBusInterface::class);
- $bus->expects($this->once())->method('dispatch');
-
- $busLocator = $this->createMock(ContainerInterface::class);
- $busLocator->expects($this->once())->method('has')->with('dummy-bus')->willReturn(true);
- $busLocator->expects($this->once())->method('get')->with('dummy-bus')->willReturn($bus);
-
- $command = new ConsumeMessagesCommand($busLocator, $receiverLocator, new EventDispatcher());
-
- $application = new Application();
- $application->add($command);
- $tester = new CommandTester($application->get('messenger:consume'));
- $tester->execute([
- 'receivers' => ['dummy-receiver'],
- '--bus' => 'dummy-bus',
'--limit' => 1,
]);
diff --git a/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php
index 901f70e1e1d69..f1fb57513ec19 100644
--- a/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php
+++ b/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php
@@ -16,7 +16,7 @@
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Command\FailedMessagesRetryCommand;
use Symfony\Component\Messenger\Envelope;
-use Symfony\Component\Messenger\MessageBusInterface;
+use Symfony\Component\Messenger\RoutableMessageBus;
use Symfony\Component\Messenger\Transport\Receiver\ListableReceiverInterface;
class FailedMessagesRetryCommandTest extends TestCase
@@ -29,7 +29,7 @@ public function testBasicRun()
$receiver->expects($this->exactly(2))->method('ack');
$dispatcher = new EventDispatcher();
- $bus = $this->createMock(MessageBusInterface::class);
+ $bus = $this->createMock(RoutableMessageBus::class);
// the bus should be called in the worker
$bus->expects($this->exactly(2))->method('dispatch')->willReturn(new Envelope(new \stdClass()));
diff --git a/src/Symfony/Component/Messenger/Tests/FailureIntegrationTest.php b/src/Symfony/Component/Messenger/Tests/FailureIntegrationTest.php
index 3ea7602d5237d..661a91b3f2979 100644
--- a/src/Symfony/Component/Messenger/Tests/FailureIntegrationTest.php
+++ b/src/Symfony/Component/Messenger/Tests/FailureIntegrationTest.php
@@ -23,10 +23,10 @@
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
-use Symfony\Component\Messenger\Middleware\FailedMessageProcessingMiddleware;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Middleware\SendMessageMiddleware;
use Symfony\Component\Messenger\Retry\MultiplierRetryStrategy;
+use Symfony\Component\Messenger\RoutableMessageBus;
use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
use Symfony\Component\Messenger\Stamp\SentToFailureTransportStamp;
use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;
@@ -90,24 +90,28 @@ public function testRequeMechanism()
],
]);
- $dispatcher = new EventDispatcher();
$bus = new MessageBus([
- new FailedMessageProcessingMiddleware(),
new SendMessageMiddleware($senderLocator),
new HandleMessageMiddleware($handlerLocator),
]);
+ $busLocator = $this->createMock(ContainerInterface::class);
+ $busLocator->method('has')->willReturn(true);
+ $busLocator->method('get')->willReturn($bus);
+ $routableBus = new RoutableMessageBus($busLocator);
+
+ $dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new SendFailedMessageForRetryListener($locator, $retryStrategyLocator));
$dispatcher->addSubscriber(new SendFailedMessageToFailureTransportListener($failureTransport));
$dispatcher->addSubscriber(new StopWorkerOnMessageLimitListener(1));
- $runWorker = function (string $transportName) use ($transports, $bus, $dispatcher): ?\Throwable {
+ $runWorker = function (string $transportName) use ($transports, $routableBus, $dispatcher): ?\Throwable {
$throwable = null;
$failedListener = function (WorkerMessageFailedEvent $event) use (&$throwable) {
$throwable = $event->getThrowable();
};
$dispatcher->addListener(WorkerMessageFailedEvent::class, $failedListener);
- $worker = new Worker([$transportName => $transports[$transportName]], $bus, $dispatcher);
+ $worker = new Worker([$transportName => $transports[$transportName]], $routableBus, $dispatcher);
$worker->run();
diff --git a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php
index 4e1c2f6982d2e..d2d0c4159f74e 100644
--- a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php
+++ b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php
@@ -17,7 +17,7 @@
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
-use Symfony\Component\Messenger\Stamp\BusNameStamp;
+use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp;
use Symfony\Component\Messenger\Stamp\DelayStamp;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
use Symfony\Component\Messenger\Tests\Fixtures\AnEnvelopeStamp;
@@ -138,13 +138,13 @@ public function testThatAMiddlewareCanUpdateTheMessageWhileKeepingTheEnvelopeSta
public function testItAddsTheStamps()
{
- $finalEnvelope = (new MessageBus())->dispatch(new \stdClass(), [new DelayStamp(5), new BusNameStamp('bar')]);
+ $finalEnvelope = (new MessageBus())->dispatch(new \stdClass(), [new DelayStamp(5), new ConsumedByWorkerStamp()]);
$this->assertCount(2, $finalEnvelope->all());
}
public function testItAddsTheStampsToEnvelope()
{
- $finalEnvelope = (new MessageBus())->dispatch(new Envelope(new \stdClass()), [new DelayStamp(5), new BusNameStamp('bar')]);
+ $finalEnvelope = (new MessageBus())->dispatch(new Envelope(new \stdClass()), [new DelayStamp(5), new ConsumedByWorkerStamp()]);
$this->assertCount(2, $finalEnvelope->all());
}
diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/AddBusNameStampMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/AddBusNameStampMiddlewareTest.php
deleted file mode 100644
index 564800f744d4d..0000000000000
--- a/src/Symfony/Component/Messenger/Tests/Middleware/AddBusNameStampMiddlewareTest.php
+++ /dev/null
@@ -1,37 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Symfony\Component\Messenger\Tests\Middleware;
-
-use Symfony\Component\Messenger\Envelope;
-use Symfony\Component\Messenger\Middleware\AddBusNameStampMiddleware;
-use Symfony\Component\Messenger\Stamp\BusNameStamp;
-use Symfony\Component\Messenger\Test\Middleware\MiddlewareTestCase;
-use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;
-
-class AddBusNameStampMiddlewareTest extends MiddlewareTestCase
-{
- public function testItSendsTheMessageToAssignedSender()
- {
- $middleware = new AddBusNameStampMiddleware('the_bus_name');
- $envelope = new Envelope(new DummyMessage('the message'));
-
- $finalEnvelope = $middleware->handle($envelope, $this->getStackMock());
- /** @var BusNameStamp $busNameStamp */
- $busNameStamp = $finalEnvelope->last(BusNameStamp::class);
- $this->assertNotNull($busNameStamp);
- $this->assertSame('the_bus_name', $busNameStamp->getBusName());
-
- // the stamp should not be added over and over again
- $finalEnvelope = $middleware->handle($finalEnvelope, $this->getStackMock());
- $this->assertCount(1, $finalEnvelope->all(BusNameStamp::class));
- }
-}
diff --git a/src/Symfony/Component/Messenger/Tests/RoutableMessageBusTest.php b/src/Symfony/Component/Messenger/Tests/RoutableMessageBusTest.php
index a41373523dad6..881121188e432 100644
--- a/src/Symfony/Component/Messenger/Tests/RoutableMessageBusTest.php
+++ b/src/Symfony/Component/Messenger/Tests/RoutableMessageBusTest.php
@@ -17,52 +17,53 @@
use Symfony\Component\Messenger\Exception\InvalidArgumentException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\RoutableMessageBus;
-use Symfony\Component\Messenger\Stamp\BusNameStamp;
use Symfony\Component\Messenger\Stamp\DelayStamp;
+use Symfony\Component\Messenger\Stamp\ReceivedStamp;
+use Symfony\Component\Messenger\Stamp\SentToFailureTransportStamp;
class RoutableMessageBusTest extends TestCase
{
public function testItRoutesToTheCorrectBus()
{
- $envelope = new Envelope(new \stdClass(), [new BusNameStamp('foo_bus')]);
+ $envelope = new Envelope(new \stdClass(), [new ReceivedStamp('foo_receiver')]);
- $bus1 = $this->createMock(MessageBusInterface::class);
- $bus2 = $this->createMock(MessageBusInterface::class);
+ $bus = $this->createMock(MessageBusInterface::class);
$container = $this->createMock(ContainerInterface::class);
- $container->expects($this->once())->method('has')->with('foo_bus')->willReturn(true);
- $container->expects($this->once())->method('get')->willReturn($bus2);
+ $container->expects($this->once())->method('has')->with('foo_receiver')->willReturn(true);
+ $container->expects($this->once())->method('get')->with('foo_receiver')->willReturn($bus);
$stamp = new DelayStamp(5);
- $bus1->expects($this->never())->method('dispatch');
- $bus2->expects($this->once())->method('dispatch')->with($envelope, [$stamp])->willReturn($envelope);
+ $bus->expects($this->once())->method('dispatch')->with($envelope, [$stamp])->willReturn($envelope);
$routableBus = new RoutableMessageBus($container);
$this->assertSame($envelope, $routableBus->dispatch($envelope, [$stamp]));
}
- public function testItRoutesToDefaultBus()
+ public function testItRoutesToTheCorrectBusWhenComingFromFailureTransport()
{
- $envelope = new Envelope(new \stdClass());
- $stamp = new DelayStamp(5);
- $defaultBus = $this->createMock(MessageBusInterface::class);
- $defaultBus->expects($this->once())->method('dispatch')->with($envelope, [$stamp])
- ->willReturn($envelope);
+ $envelope = new Envelope(new \stdClass(), [new ReceivedStamp('failure_transport'), new SentToFailureTransportStamp('original_receiver')]);
+
+ $bus = $this->createMock(MessageBusInterface::class);
$container = $this->createMock(ContainerInterface::class);
+ $container->expects($this->atLeastOnce())->method('has')->with('original_receiver')->willReturn(true);
+ $container->expects($this->once())->method('get')->with('original_receiver')->willReturn($bus);
- $routableBus = new RoutableMessageBus($container, $defaultBus);
+ $stamp = new DelayStamp(5);
+ $bus->expects($this->once())->method('dispatch')->willReturnArgument(0);
- $this->assertSame($envelope, $routableBus->dispatch($envelope, [$stamp]));
+ $routableBus = new RoutableMessageBus($container);
+ $this->assertEquals($envelope->with(new ReceivedStamp('original_receiver')), $routableBus->dispatch($envelope, [$stamp]));
}
- public function testItExceptionOnBusNotFound()
+ public function testExceptionOnBusNotFound()
{
$this->expectException(InvalidArgumentException::class);
- $this->expectExceptionMessage('Bus named "my_cool_bus" does not exist.');
+ $this->expectExceptionMessage('Could not find a bus for transport "my_cool_receiver".');
$envelope = new Envelope(new \stdClass(), [
- new BusNameStamp('my_cool_bus'),
+ new ReceivedStamp('my_cool_receiver'),
]);
$container = $this->createMock(ContainerInterface::class);
@@ -70,10 +71,10 @@ public function testItExceptionOnBusNotFound()
$routableBus->dispatch($envelope);
}
- public function testItExceptionOnDefaultBusNotFound()
+ public function testExceptionOnReceivedStampNotFound()
{
$this->expectException(InvalidArgumentException::class);
- $this->expectExceptionMessage('Envelope is missing a BusNameStamp and no fallback message bus is configured on RoutableMessageBus.');
+ $this->expectExceptionMessage('Envelope is missing a ReceivedStamp.');
$envelope = new Envelope(new \stdClass());