StackMiddleware.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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|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. public $iterator;
  59. public $stack = [];
  60. public function next(int $offset): ?MiddlewareInterface
  61. {
  62. if (isset($this->stack[$offset])) {
  63. return $this->stack[$offset];
  64. }
  65. if (null === $this->iterator) {
  66. return null;
  67. }
  68. $this->iterator->next();
  69. if (!$this->iterator->valid()) {
  70. return $this->iterator = null;
  71. }
  72. return $this->stack[] = $this->iterator->current();
  73. }
  74. }