vendor/shopware/storefront/Framework/Routing/StorefrontSubscriber.php line 318

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 $scope */
  228.         $scope $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, new RouteScope(['scopes' => []]));
  229.         if (!$scope->hasScope(StorefrontRouteScope::ID)) {
  230.             return;
  231.         }
  232.         $controller $event->getController();
  233.         // happens if Controller is a closure
  234.         if (!\is_array($controller)) {
  235.             return;
  236.         }
  237.         $isAllowed $event->getRequest()->attributes->getBoolean('XmlHttpRequest'false);
  238.         if ($isAllowed) {
  239.             return;
  240.         }
  241.         throw new AccessDeniedHttpException('PageController can\'t be requested via XmlHttpRequest.');
  242.     }
  243.     // used to switch session token - when the context token expired
  244.     public function replaceContextToken(SalesChannelContextResolvedEvent $event): void
  245.     {
  246.         $context $event->getSalesChannelContext();
  247.         // only update session if token expired and switched
  248.         if ($event->getUsedToken() === $context->getToken()) {
  249.             return;
  250.         }
  251.         $this->updateSession($context->getToken());
  252.     }
  253.     public function setCanonicalUrl(BeforeSendResponseEvent $event): void
  254.     {
  255.         if (!$event->getResponse()->isSuccessful()) {
  256.             return;
  257.         }
  258.         if ($canonical $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK)) {
  259.             $canonical sprintf('<%s>; rel="canonical"'$canonical);
  260.             $event->getResponse()->headers->set('Link'$canonical);
  261.         }
  262.     }
  263.     public function replaceCsrfToken(BeforeSendResponseEvent $event): void
  264.     {
  265.         $event->setResponse(
  266.             $this->csrfPlaceholderHandler->replaceCsrfToken($event->getResponse(), $event->getRequest())
  267.         );
  268.     }
  269.     public function addHreflang(StorefrontRenderEvent $event): void
  270.     {
  271.         $request $event->getRequest();
  272.         $route $request->attributes->get('_route');
  273.         if ($route === null) {
  274.             return;
  275.         }
  276.         $routeParams $request->attributes->get('_route_params', []);
  277.         $salesChannelContext $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  278.         $parameter = new HreflangLoaderParameter($route$routeParams$salesChannelContext);
  279.         $event->setParameter('hrefLang'$this->hreflangLoader->load($parameter));
  280.     }
  281.     public function addShopIdParameter(StorefrontRenderEvent $event): void
  282.     {
  283.         if (!$this->activeAppsLoader->getActiveApps()) {
  284.             return;
  285.         }
  286.         try {
  287.             $shopId $this->shopIdProvider->getShopId();
  288.         } catch (AppUrlChangeDetectedException $e) {
  289.             return;
  290.         }
  291.         $event->setParameter('appShopId'$shopId);
  292.     }
  293.     public function addIconSetConfig(StorefrontRenderEvent $event): void
  294.     {
  295.         $request $event->getRequest();
  296.         // get name if theme is not inherited
  297.         $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_NAME);
  298.         if (!$theme) {
  299.             // get theme name from base theme because for inherited themes the name is always null
  300.             $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_BASE_NAME);
  301.         }
  302.         if (!$theme) {
  303.             return;
  304.         }
  305.         $themeConfig $this->themeRegistry->getConfigurations()->getByTechnicalName($theme);
  306.         if (!$themeConfig) {
  307.             return;
  308.         }
  309.         $iconConfig = [];
  310.         foreach ($themeConfig->getIconSets() as $pack => $path) {
  311.             $iconConfig[$pack] = [
  312.                 'path' => $path,
  313.                 'namespace' => $theme,
  314.             ];
  315.         }
  316.         $event->setParameter('themeIconConfig'$iconConfig);
  317.     }
  318.     private function setSalesChannelContext(ExceptionEvent $event): void
  319.     {
  320.         $contextToken = (string) $event->getRequest()->headers->get(PlatformRequest::HEADER_CONTEXT_TOKEN);
  321.         $salesChannelId = (string) $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  322.         $context $this->contextService->get(
  323.             new SalesChannelContextServiceParameters(
  324.                 $salesChannelId,
  325.                 $contextToken,
  326.                 $event->getRequest()->headers->get(PlatformRequest::HEADER_LANGUAGE_ID),
  327.                 $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_CURRENCY_ID),
  328.                 $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_DOMAIN_ID)
  329.             )
  330.         );
  331.         $event->getRequest()->attributes->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT$context);
  332.     }
  333.     private function shouldRenewToken(SessionInterface $session, ?string $salesChannelId null): bool
  334.     {
  335.         if (!$session->has(PlatformRequest::HEADER_CONTEXT_TOKEN) || $salesChannelId === null) {
  336.             return true;
  337.         }
  338.         if ($this->systemConfigService->get('core.systemWideLoginRegistration.isCustomerBoundToSalesChannel')) {
  339.             return $session->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID) !== $salesChannelId;
  340.         }
  341.         return false;
  342.     }
  343. }