StackMiddleware.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\Middleware;
  11. use Symfony\Component\Messenger\Envelope;
  12. /**
  13. * @author Nicolas Grekas <p@tchwork.com>
  14. */
  15. class StackMiddleware implements MiddlewareInterface, StackInterface
  16. {
  17. private $stack;
  18. private $offset = 0;
  19. /**
  20. * @param iterable<mixed, MiddlewareInterface>|MiddlewareInterface|null $middlewareIterator
  21. */
  22. public function __construct($middlewareIterator = null)
  23. {
  24. $this->stack = new MiddlewareStack();
  25. if (null === $middlewareIterator) {
  26. return;
  27. }
  28. if ($middlewareIterator instanceof \Iterator) {
  29. $this->stack->iterator = $middlewareIterator;
  30. } elseif ($middlewareIterator instanceof MiddlewareInterface) {
  31. $this->stack->stack[] = $middlewareIterator;
  32. } elseif (!is_iterable($middlewareIterator)) {
  33. throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be iterable of "%s", "%s" given.', __METHOD__, MiddlewareInterface::class, get_debug_type($middlewareIterator)));
  34. } else {
  35. $this->stack->iterator = (function () use ($middlewareIterator) {
  36. yield from $middlewareIterator;
  37. })();
  38. }
  39. }
  40. public function next(): MiddlewareInterface
  41. {
  42. if (null === $next = $this->stack->next($this->offset)) {
  43. return $this;
  44. }
  45. ++$this->offset;
  46. return $next;
  47. }
  48. public function handle(Envelope $envelope, StackInterface $stack): Envelope
  49. {
  50. return $envelope;
  51. }
  52. }
  53. /**
  54. * @internal
  55. */
  56. class MiddlewareStack
  57. {
  58. /** @var \Iterator<mixed, MiddlewareInterface> */
  59. public $iterator;
  60. public $stack = [];
  61. public function next(int $offset): ?MiddlewareInterface
  62. {
  63. if (isset($this->stack[$offset])) {
  64. return $this->stack[$offset];
  65. }
  66. if (null === $this->iterator) {
  67. return null;
  68. }
  69. $this->iterator->next();
  70. if (!$this->iterator->valid()) {
  71. return $this->iterator = null;
  72. }
  73. return $this->stack[] = $this->iterator->current();
  74. }
  75. }