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

  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\Log\Package;
  12. use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
  13. use Shopware\Core\Framework\Routing\KernelListenerPriorities;
  14. use Shopware\Core\Framework\Util\Random;
  15. use Shopware\Core\PlatformRequest;
  16. use Shopware\Core\SalesChannelRequest;
  17. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  18. use Shopware\Core\System\SystemConfig\SystemConfigService;
  19. use Shopware\Storefront\Event\StorefrontRenderEvent;
  20. use Shopware\Storefront\Theme\StorefrontPluginRegistryInterface;
  21. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  22. use Symfony\Component\HttpFoundation\RedirectResponse;
  23. use Symfony\Component\HttpFoundation\RequestStack;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  26. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  27. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  28. use Symfony\Component\HttpKernel\Event\RequestEvent;
  29. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  30. use Symfony\Component\HttpKernel\KernelEvents;
  31. use Symfony\Component\Routing\RouterInterface;
  32. /**
  33.  * @internal
  34.  */
  35. #[Package('storefront')]
  36. class StorefrontSubscriber implements EventSubscriberInterface
  37. {
  38.     /**
  39.      * @internal
  40.      */
  41.     public function __construct(
  42.         private readonly RequestStack $requestStack,
  43.         private readonly RouterInterface $router,
  44.         private readonly HreflangLoaderInterface $hreflangLoader,
  45.         private readonly MaintenanceModeResolver $maintenanceModeResolver,
  46.         private readonly ShopIdProvider $shopIdProvider,
  47.         private readonly ActiveAppsLoader $activeAppsLoader,
  48.         private readonly SystemConfigService $systemConfigService,
  49.         private readonly StorefrontPluginRegistryInterface $themeRegistry
  50.     ) {
  51.     }
  52.     public static function getSubscribedEvents(): array
  53.     {
  54.         return [
  55.             KernelEvents::REQUEST => [
  56.                 ['startSession'40],
  57.                 ['maintenanceResolver'],
  58.             ],
  59.             KernelEvents::EXCEPTION => [
  60.                 ['customerNotLoggedInHandler'],
  61.                 ['maintenanceResolver'],
  62.             ],
  63.             KernelEvents::CONTROLLER => [
  64.                 ['preventPageLoadingFromXmlHttpRequest'KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE],
  65.             ],
  66.             CustomerLoginEvent::class => [
  67.                 'updateSessionAfterLogin',
  68.             ],
  69.             CustomerLogoutEvent::class => [
  70.                 'updateSessionAfterLogout',
  71.             ],
  72.             StorefrontRenderEvent::class => [
  73.                 ['addHreflang'],
  74.                 ['addShopIdParameter'],
  75.                 ['addIconSetConfig'],
  76.             ],
  77.             SalesChannelContextResolvedEvent::class => [
  78.                 ['replaceContextToken'],
  79.             ],
  80.         ];
  81.     }
  82.     public function startSession(): void
  83.     {
  84.         $master $this->requestStack->getMainRequest();
  85.         if (!$master) {
  86.             return;
  87.         }
  88.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  89.             return;
  90.         }
  91.         if (!$master->hasSession()) {
  92.             return;
  93.         }
  94.         $session $master->getSession();
  95.         if (!$session->isStarted()) {
  96.             $session->setName('session-');
  97.             $session->start();
  98.             $session->set('sessionId'$session->getId());
  99.         }
  100.         $salesChannelId $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  101.         if ($salesChannelId === null) {
  102.             /** @var SalesChannelContext|null $salesChannelContext */
  103.             $salesChannelContext $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  104.             if ($salesChannelContext !== null) {
  105.                 $salesChannelId $salesChannelContext->getSalesChannel()->getId();
  106.             }
  107.         }
  108.         if ($this->shouldRenewToken($session$salesChannelId)) {
  109.             $token Random::getAlphanumericString(32);
  110.             $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  111.             $session->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID$salesChannelId);
  112.         }
  113.         $master->headers->set(
  114.             PlatformRequest::HEADER_CONTEXT_TOKEN,
  115.             $session->get(PlatformRequest::HEADER_CONTEXT_TOKEN)
  116.         );
  117.     }
  118.     public function updateSessionAfterLogin(CustomerLoginEvent $event): void
  119.     {
  120.         $token $event->getContextToken();
  121.         $this->updateSession($token);
  122.     }
  123.     public function updateSessionAfterLogout(): void
  124.     {
  125.         $newToken Random::getAlphanumericString(32);
  126.         $this->updateSession($newTokentrue);
  127.     }
  128.     public function updateSession(string $tokenbool $destroyOldSession false): void
  129.     {
  130.         $master $this->requestStack->getMainRequest();
  131.         if (!$master) {
  132.             return;
  133.         }
  134.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  135.             return;
  136.         }
  137.         if (!$master->hasSession()) {
  138.             return;
  139.         }
  140.         $session $master->getSession();
  141.         $session->migrate($destroyOldSession);
  142.         $session->set('sessionId'$session->getId());
  143.         $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  144.         $master->headers->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  145.     }
  146.     public function customerNotLoggedInHandler(ExceptionEvent $event): void
  147.     {
  148.         if (!$event->getRequest()->attributes->has(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  149.             return;
  150.         }
  151.         if (!$event->getThrowable() instanceof CustomerNotLoggedInException) {
  152.             return;
  153.         }
  154.         $request $event->getRequest();
  155.         $parameters = [
  156.             'redirectTo' => $request->attributes->get('_route'),
  157.             'redirectParameters' => json_encode($request->attributes->get('_route_params'), \JSON_THROW_ON_ERROR),
  158.         ];
  159.         $redirectResponse = new RedirectResponse($this->router->generate('frontend.account.login.page'$parameters));
  160.         $event->setResponse($redirectResponse);
  161.     }
  162.     public function maintenanceResolver(RequestEvent $event): void
  163.     {
  164.         if ($this->maintenanceModeResolver->shouldRedirect($event->getRequest())) {
  165.             $event->setResponse(
  166.                 new RedirectResponse(
  167.                     $this->router->generate('frontend.maintenance.page'),
  168.                     RedirectResponse::HTTP_TEMPORARY_REDIRECT
  169.                 )
  170.             );
  171.         }
  172.     }
  173.     public function preventPageLoadingFromXmlHttpRequest(ControllerEvent $event): void
  174.     {
  175.         if (!$event->getRequest()->isXmlHttpRequest()) {
  176.             return;
  177.         }
  178.         /** @var list<string> $scope */
  179.         $scope $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  180.         if (!\in_array(StorefrontRouteScope::ID$scopetrue)) {
  181.             return;
  182.         }
  183.         /** @var callable(): Response $controller */
  184.         $controller $event->getController();
  185.         // happens if Controller is a closure
  186.         if (!\is_array($controller)) {
  187.             return;
  188.         }
  189.         $isAllowed $event->getRequest()->attributes->getBoolean('XmlHttpRequest');
  190.         if ($isAllowed) {
  191.             return;
  192.         }
  193.         throw new AccessDeniedHttpException('PageController can\'t be requested via XmlHttpRequest.');
  194.     }
  195.     // used to switch session token - when the context token expired
  196.     public function replaceContextToken(SalesChannelContextResolvedEvent $event): void
  197.     {
  198.         $context $event->getSalesChannelContext();
  199.         // only update session if token expired and switched
  200.         if ($event->getUsedToken() === $context->getToken()) {
  201.             return;
  202.         }
  203.         $this->updateSession($context->getToken());
  204.     }
  205.     public function addHreflang(StorefrontRenderEvent $event): void
  206.     {
  207.         $request $event->getRequest();
  208.         $route $request->attributes->get('_route');
  209.         if ($route === null) {
  210.             return;
  211.         }
  212.         $routeParams $request->attributes->get('_route_params', []);
  213.         $salesChannelContext $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  214.         $parameter = new HreflangLoaderParameter($route$routeParams$salesChannelContext);
  215.         $event->setParameter('hrefLang'$this->hreflangLoader->load($parameter));
  216.     }
  217.     public function addShopIdParameter(StorefrontRenderEvent $event): void
  218.     {
  219.         if (!$this->activeAppsLoader->getActiveApps()) {
  220.             return;
  221.         }
  222.         try {
  223.             $shopId $this->shopIdProvider->getShopId();
  224.         } catch (AppUrlChangeDetectedException) {
  225.             return;
  226.         }
  227.         $event->setParameter('appShopId'$shopId);
  228.     }
  229.     public function addIconSetConfig(StorefrontRenderEvent $event): void
  230.     {
  231.         $request $event->getRequest();
  232.         // get name if theme is not inherited
  233.         $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_NAME);
  234.         if (!$theme) {
  235.             // get theme name from base theme because for inherited themes the name is always null
  236.             $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_BASE_NAME);
  237.         }
  238.         if (!$theme) {
  239.             return;
  240.         }
  241.         $themeConfig $this->themeRegistry->getConfigurations()->getByTechnicalName($theme);
  242.         if (!$themeConfig) {
  243.             return;
  244.         }
  245.         $iconConfig = [];
  246.         foreach ($themeConfig->getIconSets() as $pack => $path) {
  247.             $iconConfig[$pack] = [
  248.                 'path' => $path,
  249.                 'namespace' => $theme,
  250.             ];
  251.         }
  252.         $event->setParameter('themeIconConfig'$iconConfig);
  253.     }
  254.     private function shouldRenewToken(SessionInterface $session, ?string $salesChannelId null): bool
  255.     {
  256.         if (!$session->has(PlatformRequest::HEADER_CONTEXT_TOKEN) || $salesChannelId === null) {
  257.             return true;
  258.         }
  259.         if ($this->systemConfigService->get('core.systemWideLoginRegistration.isCustomerBoundToSalesChannel')) {
  260.             return $session->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID) !== $salesChannelId;
  261.         }
  262.         return false;
  263.     }
  264. }