Skip to content

[Messenger] make dispatch(), handle() and send() methods return Envelope #28983

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Csrf\CsrfToken;
Expand Down Expand Up @@ -394,7 +395,7 @@ protected function isCsrfTokenValid(string $id, ?string $token): bool
*
* @final
*/
protected function dispatchMessage($message)
protected function dispatchMessage($message): Envelope
{
if (!$this->container->has('message_bus')) {
throw new \LogicException('The message bus is not enabled in your application. Try running "composer require symfony/messenger".');
Expand Down
3 changes: 1 addition & 2 deletions src/Symfony/Component/Messenger/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ CHANGELOG

* The component is not experimental anymore
* All the changes below are BC BREAKS
* `MessageBusInterface::dispatch()` and `MiddlewareInterface::handle()` now return `void`
* `MessageBusInterface::dispatch()`, `MiddlewareInterface::handle()` and `SenderInterface::send()` return `Envelope`
* `MiddlewareInterface::handle()` now require an `Envelope` as first argument and a `StackInterface` as second
* `EnvelopeAwareInterface` has been removed
* The signature of `Amqp*` classes changed to take a `Connection` as a first argument and an optional
Expand All @@ -31,7 +31,6 @@ CHANGELOG
* `AbstractHandlerLocator` is now internal
* `HandlerLocatorInterface::resolve()` has been replaced by `getHandler(Envelope $envelope): ?callable` and shouldn't throw when no handlers are found
* `SenderLocatorInterface::getSenderForMessage()` has been replaced by `getSender(Envelope $envelope)`
* `SenderInterface::send()` returns `void`
* Classes in the `Middleware\Enhancers` sub-namespace have been moved to the `Middleware` one
* Classes in the `Asynchronous\Routing` sub-namespace have been moved to the `Transport\Sender\Locator` sub-namespace
* The `Asynchronous/Middleware/SendMessageMiddleware` class has been moved to the `Middleware` namespace
Expand Down
7 changes: 4 additions & 3 deletions src/Symfony/Component/Messenger/MessageBus.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ public function getIterator()
/**
* {@inheritdoc}
*/
public function dispatch($message): void
public function dispatch($message): Envelope
{
if (!\is_object($message)) {
throw new \TypeError(sprintf('Invalid argument provided to "%s()": expected object, but got %s.', __METHOD__, \gettype($message)));
}
$envelope = $message instanceof Envelope ? $message : new Envelope($message);
$middlewareIterator = $this->middlewareAggregate->getIterator();

while ($middlewareIterator instanceof \IteratorAggregate) {
Expand All @@ -63,10 +64,10 @@ public function dispatch($message): void
$middlewareIterator->rewind();

if (!$middlewareIterator->valid()) {
return;
return $envelope;
}
$stack = new StackMiddleware($middlewareIterator);

$middlewareIterator->current()->handle($message instanceof Envelope ? $message : new Envelope($message), $stack);
return $middlewareIterator->current()->handle($envelope, $stack);
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/Messenger/MessageBusInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ interface MessageBusInterface
*
* @param object|Envelope $message The message or the message pre-wrapped in an envelope
*/
public function dispatch($message): void;
public function dispatch($message): Envelope;
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ public function __construct(MiddlewareInterface $inner, $activated)
/**
* {@inheritdoc}
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
if (\is_callable($this->activated) ? ($this->activated)($envelope) : $this->activated) {
$this->inner->handle($envelope, $stack);
} else {
$stack->next()->handle($envelope, $stack);
return $this->inner->handle($envelope, $stack);
}

return $stack->next()->handle($envelope, $stack);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,14 @@ public function __construct(HandlerLocatorInterface $messageHandlerLocator, bool
*
* @throws NoHandlerForMessageException When no handler is found and $allowNoHandlers is false
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
if (null !== $handler = $this->messageHandlerLocator->getHandler($envelope)) {
$handler($envelope->getMessage());
$stack->next()->handle($envelope, $stack);
} elseif (!$this->allowNoHandlers) {
throw new NoHandlerForMessageException(sprintf('No handler for message "%s".', \get_class($envelope->getMessage())));
}

return $stack->next()->handle($envelope, $stack);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct(LoggerInterface $logger)
/**
* {@inheritdoc}
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$message = $envelope->getMessage();
$context = array(
Expand All @@ -39,7 +39,7 @@ public function handle(Envelope $envelope, StackInterface $stack): void
$this->logger->debug('Starting handling message {name}', $context);

try {
$stack->next()->handle($envelope, $stack);
$envelope = $stack->next()->handle($envelope, $stack);
} catch (\Throwable $e) {
$context['exception'] = $e;
$this->logger->warning('An exception occurred while handling message {name}', $context);
Expand All @@ -48,5 +48,7 @@ public function handle(Envelope $envelope, StackInterface $stack): void
}

$this->logger->debug('Finished handling message {name}', $context);

return $envelope;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
*/
interface MiddlewareInterface
{
public function handle(Envelope $envelope, StackInterface $stack): void;
public function handle(Envelope $envelope, StackInterface $stack): Envelope;
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,24 @@ public function __construct(SenderLocatorInterface $senderLocator, array $messag
/**
* {@inheritdoc}
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
if ($envelope->get(ReceivedStamp::class)) {
// It's a received message. Do not send it back:
$stack->next()->handle($envelope, $stack);

return;
return $stack->next()->handle($envelope, $stack);
}

$sender = $this->senderLocator->getSender($envelope);

if ($sender) {
$sender->send($envelope);
$envelope = $sender->send($envelope);

if (!AbstractSenderLocator::getValueFromMessageRouting($this->messagesToSendAndHandleMapping, $envelope)) {
// message has no corresponding handler
return;
return $envelope;
}
}

$stack->next()->handle($envelope, $stack);
return $stack->next()->handle($envelope, $stack);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public function next(): MiddlewareInterface
return $iterator->current();
}

public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
// no-op: this is the last null middleware
return $envelope;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct(MiddlewareInterface $inner, Stopwatch $stopwatch, st
/**
* {@inheritdoc}
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$class = \get_class($this->inner);
$eventName = 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).'@anonymous' : $class;
Expand All @@ -49,7 +49,7 @@ public function handle(Envelope $envelope, StackInterface $stack): void
$this->stopwatch->start($eventName, $this->eventCategory);

try {
$this->inner->handle($envelope, new TraceableInnerMiddleware($stack, $this->stopwatch, $eventName, $this->eventCategory));
return $this->inner->handle($envelope, new TraceableInnerMiddleware($stack, $this->stopwatch, $eventName, $this->eventCategory));
} finally {
if ($this->stopwatch->isStarted($eventName)) {
$this->stopwatch->stop($eventName);
Expand Down Expand Up @@ -79,15 +79,17 @@ public function __construct(StackInterface $stack, Stopwatch $stopwatch, string
/**
* {@inheritdoc}
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$this->stopwatch->stop($this->eventName);
if ($this === $stack) {
$this->stack->next()->handle($envelope, $this->stack);
$envelope = $this->stack->next()->handle($envelope, $this->stack);
} else {
$stack->next()->handle($envelope, $stack);
$envelope = $stack->next()->handle($envelope, $stack);
}
$this->stopwatch->start($this->eventName, $this->eventCategory);

return $envelope;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function __construct(ValidatorInterface $validator)
/**
* {@inheritdoc}
*/
public function handle(Envelope $envelope, StackInterface $stack): void
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$message = $envelope->getMessage();
$groups = null;
Expand All @@ -45,6 +45,6 @@ public function handle(Envelope $envelope, StackInterface $stack): void
throw new ValidationFailedException($message, $violations);
}

$stack->next()->handle($envelope, $stack);
return $stack->next()->handle($envelope, $stack);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Messenger\DataCollector\MessengerDataCollector;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;
use Symfony\Component\Messenger\TraceableMessageBus;
Expand All @@ -36,9 +37,10 @@ protected function setUp()
public function testHandle()
{
$message = new DummyMessage('dummy message');
$envelope = new Envelope($message);

$bus = $this->getMockBuilder(MessageBusInterface::class)->getMock();
$bus->method('dispatch')->with($message);
$bus->method('dispatch')->with($message)->willReturn($envelope);
$bus = new TraceableMessageBus($bus);

$collector = new MessengerDataCollector();
Expand Down Expand Up @@ -124,9 +126,11 @@ public function testHandleWithException()
public function testKeepsOrderedDispatchCalls()
{
$firstBus = $this->getMockBuilder(MessageBusInterface::class)->getMock();
$firstBus->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$firstBus = new TraceableMessageBus($firstBus);

$secondBus = $this->getMockBuilder(MessageBusInterface::class)->getMock();
$secondBus->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$secondBus = new TraceableMessageBus($secondBus);

$collector = new MessengerDataCollector();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,8 @@ public function dummyMethodForSomeBus()

class UselessMiddleware implements MiddlewareInterface
{
public function handle(Envelope $message, StackInterface $stack): void
public function handle(Envelope $message, StackInterface $stack): Envelope
{
$stack->next()->handle($message, $stack);
return $stack->next()->handle($message, $stack);
}
}
11 changes: 7 additions & 4 deletions src/Symfony/Component/Messenger/Tests/MessageBusTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,14 @@ public function testItCallsMiddleware()
->method('handle')
->with($envelope, $this->anything())
->will($this->returnCallback(function ($envelope, $stack) {
$stack->next()->handle($envelope, $stack);
return $stack->next()->handle($envelope, $stack);
}));

$secondMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock();
$secondMiddleware->expects($this->once())
->method('handle')
->with($envelope, $this->anything())
->willReturn($envelope)
;

$bus = new MessageBus(array(
Expand All @@ -77,21 +78,22 @@ public function testThatAMiddlewareCanAddSomeStampsToTheEnvelope()
->method('handle')
->with($envelope, $this->anything())
->will($this->returnCallback(function ($envelope, $stack) {
$stack->next()->handle($envelope->with(new AnEnvelopeStamp()), $stack);
return $stack->next()->handle($envelope->with(new AnEnvelopeStamp()), $stack);
}));

$secondMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock();
$secondMiddleware->expects($this->once())
->method('handle')
->with($envelopeWithAnotherStamp, $this->anything())
->will($this->returnCallback(function ($envelope, $stack) {
$stack->next()->handle($envelope, $stack);
return $stack->next()->handle($envelope, $stack);
}));

$thirdMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock();
$thirdMiddleware->expects($this->once())
->method('handle')
->with($envelopeWithAnotherStamp, $this->anything())
->willReturn($envelopeWithAnotherStamp)
;

$bus = new MessageBus(array(
Expand All @@ -116,13 +118,14 @@ public function testThatAMiddlewareCanUpdateTheMessageWhileKeepingTheEnvelopeSta
->method('handle')
->with($envelope, $this->anything())
->will($this->returnCallback(function ($envelope, $stack) use ($expectedEnvelope) {
$stack->next()->handle($expectedEnvelope, $stack);
return $stack->next()->handle($expectedEnvelope, $stack);
}));

$secondMiddleware = $this->getMockBuilder(MiddlewareInterface::class)->getMock();
$secondMiddleware->expects($this->once())
->method('handle')
->with($expectedEnvelope, $this->anything())
->willReturn($envelope)
;

$bus = new MessageBus(array(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function testExecuteMiddlewareOnActivated()
$stack->expects($this->never())->method('next');

$middleware = $this->createMock(MiddlewareInterface::class);
$middleware->expects($this->once())->method('handle')->with($envelope, $stack);
$middleware->expects($this->once())->method('handle')->with($envelope, $stack)->willReturn($envelope);

$decorator = new ActivationMiddleware($middleware, true);

Expand All @@ -50,7 +50,7 @@ public function testExecuteMiddlewareOnActivatedWithCallable()
$stack->expects($this->never())->method('next');

$middleware = $this->createMock(MiddlewareInterface::class);
$middleware->expects($this->once())->method('handle')->with($envelope, $stack);
$middleware->expects($this->once())->method('handle')->with($envelope, $stack)->willReturn($envelope);

$decorator = new ActivationMiddleware($middleware, $activated);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,6 @@ public function testAllowNoHandlers()
{
$middleware = new HandleMessageMiddleware(new HandlerLocator(array()), true);

$this->assertNull($middleware->handle(new Envelope(new DummyMessage('Hey')), new StackMiddleware()));
$this->assertInstanceOf(Envelope::class, $middleware->handle(new Envelope(new DummyMessage('Hey')), new StackMiddleware()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ protected function getStackMock(bool $nextIsCalled = true)
$nextMiddleware
->expects($nextIsCalled ? $this->once() : $this->never())
->method('handle')
->will($this->returnCallback(function ($envelope, StackInterface $stack) {
return $envelope;
}))
;

$stack = $this->createMock(StackInterface::class);
Expand Down
Loading