vendor/shopware/platform/src/Storefront/Framework/Routing/StorefrontSubscriber.php line 298

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Routing;
  3. use Shopware\Core\Checkout\Cart\Exception\CustomerNotLoggedInException;
  4. use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
  5. use Shopware\Core\Checkout\Customer\Event\CustomerLogoutEvent;
  6. use Shopware\Core\Content\Seo\HreflangLoaderInterface;
  7. use Shopware\Core\Content\Seo\HreflangLoaderParameter;
  8. use Shopware\Core\Framework\App\ActiveAppsLoader;
  9. use Shopware\Core\Framework\App\Exception\AppUrlChangeDetectedException;
  10. use Shopware\Core\Framework\App\ShopId\ShopIdProvider;
  11. use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
  12. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  13. use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
  14. use Shopware\Core\Framework\Routing\KernelListenerPriorities;
  15. use Shopware\Core\Framework\Util\Random;
  16. use Shopware\Core\PlatformRequest;
  17. use Shopware\Core\SalesChannelRequest;
  18. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextServiceInterface;
  19. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextServiceParameters;
  20. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  21. use Shopware\Core\System\SystemConfig\SystemConfigService;
  22. use Shopware\Storefront\Controller\ErrorController;
  23. use Shopware\Storefront\Event\StorefrontRenderEvent;
  24. use Shopware\Storefront\Framework\Csrf\CsrfPlaceholderHandler;
  25. use Shopware\Storefront\Theme\StorefrontPluginRegistryInterface;
  26. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  27. use Symfony\Component\HttpFoundation\RedirectResponse;
  28. use Symfony\Component\HttpFoundation\RequestStack;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  31. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  32. use Symfony\Component\HttpKernel\Event\RequestEvent;
  33. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  34. use Symfony\Component\HttpKernel\KernelEvents;
  35. use Symfony\Component\Routing\RouterInterface;
  36. class StorefrontSubscriber implements EventSubscriberInterface
  37. {
  38.     private RequestStack $requestStack;
  39.     private RouterInterface $router;
  40.     private ErrorController $errorController;
  41.     private SalesChannelContextServiceInterface $contextService;
  42.     private bool $kernelDebug;
  43.     private CsrfPlaceholderHandler $csrfPlaceholderHandler;
  44.     private MaintenanceModeResolver $maintenanceModeResolver;
  45.     private HreflangLoaderInterface $hreflangLoader;
  46.     private ShopIdProvider $shopIdProvider;
  47.     private ActiveAppsLoader $activeAppsLoader;
  48.     private SystemConfigService $systemConfigService;
  49.     private StorefrontPluginRegistryInterface $themeRegistry;
  50.     public function __construct(
  51.         RequestStack $requestStack,
  52.         RouterInterface $router,
  53.         ErrorController $errorController,
  54.         SalesChannelContextServiceInterface $contextService,
  55.         CsrfPlaceholderHandler $csrfPlaceholderHandler,
  56.         HreflangLoaderInterface $hreflangLoader,
  57.         bool $kernelDebug,
  58.         MaintenanceModeResolver $maintenanceModeResolver,
  59.         ShopIdProvider $shopIdProvider,
  60.         ActiveAppsLoader $activeAppsLoader,
  61.         SystemConfigService $systemConfigService,
  62.         StorefrontPluginRegistryInterface $themeRegistry
  63.     ) {
  64.         $this->requestStack $requestStack;
  65.         $this->router $router;
  66.         $this->errorController $errorController;
  67.         $this->contextService $contextService;
  68.         $this->kernelDebug $kernelDebug;
  69.         $this->csrfPlaceholderHandler $csrfPlaceholderHandler;
  70.         $this->maintenanceModeResolver $maintenanceModeResolver;
  71.         $this->hreflangLoader $hreflangLoader;
  72.         $this->shopIdProvider $shopIdProvider;
  73.         $this->activeAppsLoader $activeAppsLoader;
  74.         $this->systemConfigService $systemConfigService;
  75.         $this->themeRegistry $themeRegistry;
  76.     }
  77.     public static function getSubscribedEvents(): array
  78.     {
  79.         return [
  80.             KernelEvents::REQUEST => [
  81.                 ['startSession'40],
  82.                 ['maintenanceResolver'],
  83.             ],
  84.             KernelEvents::EXCEPTION => [
  85.                 ['showHtmlExceptionResponse', -100],
  86.                 ['customerNotLoggedInHandler'],
  87.                 ['maintenanceResolver'],
  88.             ],
  89.             KernelEvents::CONTROLLER => [
  90.                 ['preventPageLoadingFromXmlHttpRequest'KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE],
  91.             ],
  92.             CustomerLoginEvent::class => [
  93.                 'updateSessionAfterLogin',
  94.             ],
  95.             CustomerLogoutEvent::class => [
  96.                 'updateSessionAfterLogout',
  97.             ],
  98.             BeforeSendResponseEvent::class => [
  99.                 ['replaceCsrfToken'],
  100.                 ['setCanonicalUrl'],
  101.             ],
  102.             StorefrontRenderEvent::class => [
  103.                 ['addHreflang'],
  104.                 ['addShopIdParameter'],
  105.                 ['addIconSetConfig'],
  106.             ],
  107.             SalesChannelContextResolvedEvent::class => [
  108.                 ['replaceContextToken'],
  109.             ],
  110.         ];
  111.     }
  112.     public function startSession(): void
  113.     {
  114.         $master $this->requestStack->getMainRequest();
  115.         if (!$master) {
  116.             return;
  117.         }
  118.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  119.             return;
  120.         }
  121.         if (!$master->hasSession()) {
  122.             return;
  123.         }
  124.         $session $master->getSession();
  125.         if (!$session->isStarted()) {
  126.             $session->setName('session-');
  127.             $session->start();
  128.             $session->set('sessionId'$session->getId());
  129.         }
  130.         $salesChannelId $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  131.         if ($salesChannelId === null) {
  132.             /** @var SalesChannelContext|null $salesChannelContext */
  133.             $salesChannelContext $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  134.             if ($salesChannelContext !== null) {
  135.                 $salesChannelId $salesChannelContext->getSalesChannel()->getId();
  136.             }
  137.         }
  138.         if ($this->shouldRenewToken($session$salesChannelId)) {
  139.             $token Random::getAlphanumericString(32);
  140.             $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  141.             $session->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID$salesChannelId);
  142.         }
  143.         $master->headers->set(
  144.             PlatformRequest::HEADER_CONTEXT_TOKEN,
  145.             $session->get(PlatformRequest::HEADER_CONTEXT_TOKEN)
  146.         );
  147.     }
  148.     public function updateSessionAfterLogin(CustomerLoginEvent $event): void
  149.     {
  150.         $token $event->getContextToken();
  151.         $this->updateSession($token);
  152.     }
  153.     public function updateSessionAfterLogout(): void
  154.     {
  155.         $newToken Random::getAlphanumericString(32);
  156.         $this->updateSession($newTokentrue);
  157.     }
  158.     public function updateSession(string $tokenbool $destroyOldSession false): void
  159.     {
  160.         $master $this->requestStack->getMainRequest();
  161.         if (!$master) {
  162.             return;
  163.         }
  164.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  165.             return;
  166.         }
  167.         if (!$master->hasSession()) {
  168.             return;
  169.         }
  170.         $session $master->getSession();
  171.         $session->migrate($destroyOldSession);
  172.         $session->set('sessionId'$session->getId());
  173.         $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  174.         $master->headers->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  175.     }
  176.     public function showHtmlExceptionResponse(ExceptionEvent $event): void
  177.     {
  178.         if ($this->kernelDebug || $event->getRequest()->attributes->has(SalesChannelRequest::ATTRIBUTE_STORE_API_PROXY)) {
  179.             return;
  180.         }
  181.         if (!$event->getRequest()->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)) {
  182.             //When no saleschannel context is resolved, we need to resolve it now.
  183.             $this->setSalesChannelContext($event);
  184.         }
  185.         if ($event->getRequest()->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)) {
  186.             $event->stopPropagation();
  187.             $response $this->errorController->error(
  188.                 $event->getThrowable(),
  189.                 $this->requestStack->getMainRequest(),
  190.                 $event->getRequest()->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)
  191.             );
  192.             $event->setResponse($response);
  193.         }
  194.     }
  195.     public function customerNotLoggedInHandler(ExceptionEvent $event): void
  196.     {
  197.         if (!$event->getRequest()->attributes->has(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  198.             return;
  199.         }
  200.         if (!$event->getThrowable() instanceof CustomerNotLoggedInException) {
  201.             return;
  202.         }
  203.         $request $event->getRequest();
  204.         $parameters = [
  205.             'redirectTo' => $request->attributes->get('_route'),
  206.             'redirectParameters' => json_encode($request->attributes->get('_route_params')),
  207.         ];
  208.         $redirectResponse = new RedirectResponse($this->router->generate('frontend.account.login.page'$parameters));
  209.         $event->setResponse($redirectResponse);
  210.     }
  211.     public function maintenanceResolver(RequestEvent $event): void
  212.     {
  213.         if ($this->maintenanceModeResolver->shouldRedirect($event->getRequest())) {
  214.             $event->setResponse(
  215.                 new RedirectResponse(
  216.                     $this->router->generate('frontend.maintenance.page'),
  217.                     RedirectResponse::HTTP_TEMPORARY_REDIRECT
  218.                 )
  219.             );
  220.         }
  221.     }
  222.     public function preventPageLoadingFromXmlHttpRequest(ControllerEvent $event): void
  223.     {
  224.         if (!$event->getRequest()->isXmlHttpRequest()) {
  225.             return;
  226.         }
  227.         /** @var RouteScope|array $scope */
  228.         $scope $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  229.         if ($scope instanceof RouteScope) {
  230.             $scope $scope->getScopes();
  231.         }
  232.         if (!\in_array(StorefrontRouteScope::ID$scopetrue)) {
  233.             return;
  234.         }
  235.         $controller $event->getController();
  236.         // happens if Controller is a closure
  237.         if (!\is_array($controller)) {
  238.             return;
  239.         }
  240.         $isAllowed $event->getRequest()->attributes->getBoolean('XmlHttpRequest'false);
  241.         if ($isAllowed) {
  242.             return;
  243.         }
  244.         throw new AccessDeniedHttpException('PageController can\'t be requested via XmlHttpRequest.');
  245.     }
  246.     // used to switch session token - when the context token expired
  247.     public function replaceContextToken(SalesChannelContextResolvedEvent $event): void
  248.     {
  249.         $context $event->getSalesChannelContext();
  250.         // only update session if token expired and switched
  251.         if ($event->getUsedToken() === $context->getToken()) {
  252.             return;
  253.         }
  254.         $this->updateSession($context->getToken());
  255.     }
  256.     public function setCanonicalUrl(BeforeSendResponseEvent $event): void
  257.     {
  258.         if (!$event->getResponse()->isSuccessful()) {
  259.             return;
  260.         }
  261.         if ($canonical $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK)) {
  262.             $canonical sprintf('<%s>; rel="canonical"'$canonical);
  263.             $event->getResponse()->headers->set('Link'$canonical);
  264.         }
  265.     }
  266.     public function replaceCsrfToken(BeforeSendResponseEvent $event): void
  267.     {
  268.         $event->setResponse(
  269.             $this->csrfPlaceholderHandler->replaceCsrfToken($event->getResponse(), $event->getRequest())
  270.         );
  271.     }
  272.     public function addHreflang(StorefrontRenderEvent $event): void
  273.     {
  274.         $request $event->getRequest();
  275.         $route $request->attributes->get('_route');
  276.         if ($route === null) {
  277.             return;
  278.         }
  279.         $routeParams $request->attributes->get('_route_params', []);
  280.         $salesChannelContext $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  281.         $parameter = new HreflangLoaderParameter($route$routeParams$salesChannelContext);
  282.         $event->setParameter('hrefLang'$this->hreflangLoader->load($parameter));
  283.     }
  284.     public function addShopIdParameter(StorefrontRenderEvent $event): void
  285.     {
  286.         if (!$this->activeAppsLoader->getActiveApps()) {
  287.             return;
  288.         }
  289.         try {
  290.             $shopId $this->shopIdProvider->getShopId();
  291.         } catch (AppUrlChangeDetectedException $e) {
  292.             return;
  293.         }
  294.         $event->setParameter('appShopId'$shopId);
  295.     }
  296.     public function addIconSetConfig(StorefrontRenderEvent $event): void
  297.     {
  298.         $request $event->getRequest();
  299.         // get name if theme is not inherited
  300.         $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_NAME);
  301.         if (!$theme) {
  302.             // get theme name from base theme because for inherited themes the name is always null
  303.             $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_BASE_NAME);
  304.         }
  305.         if (!$theme) {
  306.             return;
  307.         }
  308.         $themeConfig $this->themeRegistry->getConfigurations()->getByTechnicalName($theme);
  309.         if (!$themeConfig) {
  310.             return;
  311.         }
  312.         $iconConfig = [];
  313.         foreach ($themeConfig->getIconSets() as $pack => $path) {
  314.             $iconConfig[$pack] = [
  315.                 'path' => $path,
  316.                 'namespace' => $theme,
  317.             ];
  318.         }
  319.         $event->setParameter('themeIconConfig'$iconConfig);
  320.     }
  321.     private function setSalesChannelContext(ExceptionEvent $event): void
  322.     {
  323.         $contextToken = (string) $event->getRequest()->headers->get(PlatformRequest::HEADER_CONTEXT_TOKEN);
  324.         $salesChannelId = (string) $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  325.         $context $this->contextService->get(
  326.             new SalesChannelContextServiceParameters(
  327.                 $salesChannelId,
  328.                 $contextToken,
  329.                 $event->getRequest()->headers->get(PlatformRequest::HEADER_LANGUAGE_ID),
  330.                 $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_CURRENCY_ID),
  331.                 $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_ID)
  332.             )
  333.         );
  334.         $event->getRequest()->attributes->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT$context);
  335.     }
  336.     private function shouldRenewToken(SessionInterface $session, ?string $salesChannelId null): bool
  337.     {
  338.         if (!$session->has(PlatformRequest::HEADER_CONTEXT_TOKEN) || $salesChannelId === null) {
  339.             return true;
  340.         }
  341.         if ($this->systemConfigService->get('core.systemWideLoginRegistration.isCustomerBoundToSalesChannel')) {
  342.             return $session->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID) !== $salesChannelId;
  343.         }
  344.         return false;
  345.     }
  346. }