src/Storefront/Framework/Routing/NotFound/NotFoundSubscriber.php line 57

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Routing\NotFound;
  3. use Shopware\Core\Framework\Adapter\Cache\AbstractCacheTracer;
  4. use Shopware\Core\Framework\Adapter\Cache\CacheInvalidator;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
  6. use Shopware\Core\Framework\Log\Package;
  7. use Shopware\Core\Framework\Uuid\Uuid;
  8. use Shopware\Core\PlatformRequest;
  9. use Shopware\Core\SalesChannelRequest;
  10. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextServiceInterface;
  11. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextServiceParameters;
  12. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  13. use Shopware\Core\System\SystemConfig\Event\SystemConfigChangedEvent;
  14. use Shopware\Storefront\Controller\ErrorController;
  15. use Shopware\Storefront\Framework\Routing\StorefrontResponse;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\RequestStack;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  21. use Symfony\Component\HttpKernel\Exception\HttpException;
  22. use Symfony\Component\HttpKernel\KernelEvents;
  23. use Symfony\Contracts\Cache\CacheInterface;
  24. use Symfony\Contracts\Cache\ItemInterface;
  25. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  26. /**
  27.  * @internal
  28.  */
  29. #[Package('storefront')]
  30. class NotFoundSubscriber implements EventSubscriberInterface
  31. {
  32.     private const ALL_TAG 'error-page';
  33.     private const SYSTEM_CONFIG_KEY 'core.basicInformation.http404Page';
  34.     /**
  35.      * @internal
  36.      *
  37.      * @param AbstractCacheTracer<Response> $cacheTracer
  38.      */
  39.     public function __construct(private readonly ErrorController $controller, private readonly RequestStack $requestStack, private readonly SalesChannelContextServiceInterface $contextService, private bool $kernelDebug, private readonly CacheInterface $cache, private readonly AbstractCacheTracer $cacheTracer, private readonly EntityCacheKeyGenerator $generator, private readonly CacheInvalidator $cacheInvalidator, private readonly EventDispatcherInterface $eventDispatcher)
  40.     {
  41.     }
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return [
  45.             KernelEvents::EXCEPTION => [
  46.                 ['onError', -100],
  47.             ],
  48.             SystemConfigChangedEvent::class => 'onSystemConfigChanged',
  49.         ];
  50.     }
  51.     public function onError(ExceptionEvent $event): void
  52.     {
  53.         $request $event->getRequest();
  54.         if ($this->kernelDebug) {
  55.             return;
  56.         }
  57.         $event->stopPropagation();
  58.         $salesChannelId $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID'');
  59.         $domainId $request->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_ID'');
  60.         $languageId $request->attributes->get(PlatformRequest::HEADER_LANGUAGE_ID'');
  61.         if (!$request->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)) {
  62.             // When no sales-channel context is resolved, we need to resolve it now.
  63.             $this->setSalesChannelContext($request);
  64.         }
  65.         $is404StatusCode $event->getThrowable() instanceof HttpException && $event->getThrowable()->getStatusCode() === Response::HTTP_NOT_FOUND;
  66.         // If the exception is not a 404 status code, we don't need to cache it.
  67.         if (!$is404StatusCode) {
  68.             $event->setResponse($this->controller->error(
  69.                 $event->getThrowable(),
  70.                 $request,
  71.                 $event->getRequest()->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)
  72.             ));
  73.             return;
  74.         }
  75.         /** @var SalesChannelContext $context */
  76.         $context $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  77.         $name self::buildName($salesChannelId$domainId$languageId);
  78.         $key $this->generateKey($salesChannelId$domainId$languageId$request$context);
  79.         $response $this->cache->get($key, function (ItemInterface $item) use ($event$name$context) {
  80.             /** @var StorefrontResponse $response */
  81.             $response $this->cacheTracer->trace($name, function () use ($event) {
  82.                 /** @var Request $request */
  83.                 $request $this->requestStack->getMainRequest();
  84.                 return $this->controller->error(
  85.                     $event->getThrowable(),
  86.                     $request,
  87.                     $event->getRequest()->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)
  88.                 );
  89.             });
  90.             $item->tag($this->generateTags($name$event->getRequest(), $context));
  91.             $response->setData([]);
  92.             $response->setContext(null);
  93.             return $response;
  94.         });
  95.         $event->setResponse($response);
  96.     }
  97.     public function onSystemConfigChanged(SystemConfigChangedEvent $event): void
  98.     {
  99.         if ($event->getKey() !== self::SYSTEM_CONFIG_KEY) {
  100.             return;
  101.         }
  102.         $this->cacheInvalidator->invalidate([self::ALL_TAG]);
  103.     }
  104.     private static function buildName(string $salesChannelIdstring $domainIdstring $languageId): string
  105.     {
  106.         return 'error-page-' $salesChannelId $domainId $languageId;
  107.     }
  108.     private function generateKey(string $salesChannelIdstring $domainIdstring $languageIdRequest $requestSalesChannelContext $context): string
  109.     {
  110.         $key self::buildName($salesChannelId$domainId$languageId) . md5($this->generator->getSalesChannelContextHash($context));
  111.         $event = new NotFoundPageCacheKeyEvent($key$request$context);
  112.         $this->eventDispatcher->dispatch($event);
  113.         return $event->getKey();
  114.     }
  115.     /**
  116.      * @return array<string>
  117.      */
  118.     private function generateTags(string $nameRequest $requestSalesChannelContext $context): array
  119.     {
  120.         $tags array_merge(
  121.             $this->cacheTracer->get($name),
  122.             [$nameself::ALL_TAG]
  123.         );
  124.         $event = new NotFoundPageTagsEvent($tags$request$context);
  125.         $this->eventDispatcher->dispatch($event);
  126.         return array_unique(array_filter($event->getTags()));
  127.     }
  128.     private function setSalesChannelContext(Request $request): void
  129.     {
  130.         $salesChannelId = (string) $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  131.         $context $this->contextService->get(
  132.             new SalesChannelContextServiceParameters(
  133.                 $salesChannelId,
  134.                 Uuid::randomHex(),
  135.                 $request->headers->get(PlatformRequest::HEADER_LANGUAGE_ID),
  136.                 $request->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_CURRENCY_ID),
  137.                 $request->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_ID)
  138.             )
  139.         );
  140.         $request->attributes->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT$context);
  141.     }
  142. }