|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Bundle\FrameworkBundle\Messenger; |
| 13 | + |
| 14 | +use Symfony\Component\Messenger\Envelope; |
| 15 | +use Symfony\Component\Messenger\Middleware\MiddlewareInterface; |
| 16 | +use Symfony\Component\Messenger\Middleware\StackInterface; |
| 17 | +use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp; |
| 18 | +use Symfony\Component\Routing\RequestContext; |
| 19 | +use Symfony\Component\Routing\RequestContextAwareInterface; |
| 20 | + |
| 21 | +/** |
| 22 | + * Restore the Router context when processing the message. |
| 23 | + * |
| 24 | + * @author Jérémy Derussé <jeremy@derusse.com> |
| 25 | + */ |
| 26 | +class RouterContextMiddleware implements MiddlewareInterface |
| 27 | +{ |
| 28 | + private $router; |
| 29 | + |
| 30 | + public function __construct(RequestContextAwareInterface $router) |
| 31 | + { |
| 32 | + $this->router = $router; |
| 33 | + } |
| 34 | + |
| 35 | + public function handle(Envelope $envelope, StackInterface $stack): Envelope |
| 36 | + { |
| 37 | + if (null !== $envelope->last(ConsumedByWorkerStamp::class)) { |
| 38 | + /** @var RouterContextStamp $contextStamp */ |
| 39 | + if (null !== $contextStamp = $envelope->last(RouterContextStamp::class)) { |
| 40 | + $currentContext = $this->router->getContext(); |
| 41 | + |
| 42 | + $this->router->setContext(new RequestContext( |
| 43 | + $contextStamp->getBaseUrl(), |
| 44 | + $contextStamp->getMethod(), |
| 45 | + $contextStamp->getHost(), |
| 46 | + $contextStamp->getScheme(), |
| 47 | + $contextStamp->getHttpPort(), |
| 48 | + $contextStamp->getHttpsPort(), |
| 49 | + $contextStamp->getPathInfo(), |
| 50 | + $contextStamp->getQueryString() |
| 51 | + )); |
| 52 | + |
| 53 | + try { |
| 54 | + return $stack->next()->handle($envelope, $stack); |
| 55 | + } finally { |
| 56 | + $this->router->setContext($currentContext); |
| 57 | + } |
| 58 | + } |
| 59 | + } else { |
| 60 | + $context = $this->router->getContext(); |
| 61 | + $envelope = $envelope->with(new RouterContextStamp( |
| 62 | + $context->getBaseUrl(), |
| 63 | + $context->getMethod(), |
| 64 | + $context->getHost(), |
| 65 | + $context->getScheme(), |
| 66 | + $context->getHttpPort(), |
| 67 | + $context->getHttpsPort(), |
| 68 | + $context->getPathInfo(), |
| 69 | + $context->getQueryString() |
| 70 | + )); |
| 71 | + } |
| 72 | + |
| 73 | + return $stack->next()->handle($envelope, $stack); |
| 74 | + } |
| 75 | +} |
0 commit comments