HandleTrait.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Messenger;
  11. use Symfony\Component\Messenger\Exception\LogicException;
  12. use Symfony\Component\Messenger\Stamp\HandledStamp;
  13. /**
  14. * Leverages a message bus to expect a single, synchronous message handling and return its result.
  15. *
  16. * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
  17. */
  18. trait HandleTrait
  19. {
  20. /** @var MessageBusInterface */
  21. private $messageBus;
  22. /**
  23. * Dispatches the given message, expecting to be handled by a single handler
  24. * and returns the result from the handler returned value.
  25. * This behavior is useful for both synchronous command & query buses,
  26. * the last one usually returning the handler result.
  27. *
  28. * @param object|Envelope $message The message or the message pre-wrapped in an envelope
  29. *
  30. * @return mixed The handler returned value
  31. */
  32. private function handle($message)
  33. {
  34. if (!$this->messageBus instanceof MessageBusInterface) {
  35. throw new LogicException(sprintf('You must provide a "%s" instance in the "%s::$messageBus" property, "%s" given.', MessageBusInterface::class, static::class, get_debug_type($this->messageBus)));
  36. }
  37. $envelope = $this->messageBus->dispatch($message);
  38. /** @var HandledStamp[] $handledStamps */
  39. $handledStamps = $envelope->all(HandledStamp::class);
  40. if (!$handledStamps) {
  41. throw new LogicException(sprintf('Message of type "%s" was handled zero times. Exactly one handler is expected when using "%s::%s()".', get_debug_type($envelope->getMessage()), static::class, __FUNCTION__));
  42. }
  43. if (\count($handledStamps) > 1) {
  44. $handlers = implode(', ', array_map(function (HandledStamp $stamp): string {
  45. return sprintf('"%s"', $stamp->getHandlerName());
  46. }, $handledStamps));
  47. throw new LogicException(sprintf('Message of type "%s" was handled multiple times. Only one handler is expected when using "%s::%s()", got %d: %s.', get_debug_type($envelope->getMessage()), static::class, __FUNCTION__, \count($handledStamps), $handlers));
  48. }
  49. return $handledStamps[0]->getResult();
  50. }
  51. }