vendor/symfony/messenger/MessageBus.php line 70

  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\Middleware\MiddlewareInterface;
  12. use Symfony\Component\Messenger\Middleware\StackMiddleware;
  13. /**
  14.  * @author Samuel Roze <samuel.roze@gmail.com>
  15.  * @author Matthias Noback <matthiasnoback@gmail.com>
  16.  * @author Nicolas Grekas <p@tchwork.com>
  17.  */
  18. class MessageBus implements MessageBusInterface
  19. {
  20.     private \IteratorAggregate $middlewareAggregate;
  21.     /**
  22.      * @param iterable<mixed, MiddlewareInterface> $middlewareHandlers
  23.      */
  24.     public function __construct(iterable $middlewareHandlers = [])
  25.     {
  26.         if ($middlewareHandlers instanceof \IteratorAggregate) {
  27.             $this->middlewareAggregate $middlewareHandlers;
  28.         } elseif (\is_array($middlewareHandlers)) {
  29.             $this->middlewareAggregate = new \ArrayObject($middlewareHandlers);
  30.         } else {
  31.             // $this->middlewareAggregate should be an instance of IteratorAggregate.
  32.             // When $middlewareHandlers is an Iterator, we wrap it to ensure it is lazy-loaded and can be rewound.
  33.             $this->middlewareAggregate = new class($middlewareHandlers) implements \IteratorAggregate {
  34.                 private \Traversable $middlewareHandlers;
  35.                 private \ArrayObject $cachedIterator;
  36.                 public function __construct(\Traversable $middlewareHandlers)
  37.                 {
  38.                     $this->middlewareHandlers $middlewareHandlers;
  39.                 }
  40.                 public function getIterator(): \Traversable
  41.                 {
  42.                     return $this->cachedIterator ??= new \ArrayObject(iterator_to_array($this->middlewareHandlersfalse));
  43.                 }
  44.             };
  45.         }
  46.     }
  47.     public function dispatch(object $message, array $stamps = []): Envelope
  48.     {
  49.         $envelope Envelope::wrap($message$stamps);
  50.         $middlewareIterator $this->middlewareAggregate->getIterator();
  51.         while ($middlewareIterator instanceof \IteratorAggregate) {
  52.             $middlewareIterator $middlewareIterator->getIterator();
  53.         }
  54.         $middlewareIterator->rewind();
  55.         if (!$middlewareIterator->valid()) {
  56.             return $envelope;
  57.         }
  58.         $stack = new StackMiddleware($middlewareIterator);
  59.         return $middlewareIterator->current()->handle($envelope$stack);
  60.     }
  61. }