custom/plugins/KielCodingPlatformTrailingSlash/src/TrailingSlash/RequestSubscriber.php line 33

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace KielCodingPlatformTrailingSlash\TrailingSlash;
  3. use Shopware\Core\SalesChannelRequest;
  4. use Shopware\Core\System\SystemConfig\SystemConfigService;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class RequestSubscriber implements EventSubscriberInterface
  11. {
  12.     private const ROUTE_NAME 'frontend.navigation.page';
  13.     private SystemConfigService $systemConfigService;
  14.     public function __construct(SystemConfigService $systemConfigService)
  15.     {
  16.         $this->systemConfigService $systemConfigService;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::REQUEST => [
  22.                 ['onRequest'],
  23.             ],
  24.         ];
  25.     }
  26.     public function onRequest(RequestEvent $event): void
  27.     {
  28.         $request $event->getRequest();
  29.         if (!$event->isMainRequest()) {
  30.             return;
  31.         }
  32.         if (!$this->isNavigationRequest($request)) {
  33.             return;
  34.         }
  35.         if (!$this->shouldRedirect()) {
  36.             return;
  37.         }
  38.         if (!$request->attributes->has(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK)) {
  39.             return;
  40.         }
  41.         $canonical $request->attributes->get(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK);
  42.         $current $request->attributes->get(RequestTransformer::ATTRIBUTE_CURRENT_LINK);
  43.         if ($canonical === $current) {
  44.             // no redirect needed
  45.             return;
  46.         }
  47.         if ($request->getQueryString()) {
  48.             $canonical .= '?' $request->getQueryString();
  49.         }
  50.         $statusCode $this->getStatusCode();
  51.         $event->setResponse(new RedirectResponse($canonical$statusCode));
  52.     }
  53.     private function isNavigationRequest(Request $request): bool
  54.     {
  55.         return $request->attributes->get('_route') == self::ROUTE_NAME;
  56.     }
  57.     private function shouldRedirect(): bool
  58.     {
  59.         return $this->systemConfigService->getString('KielCodingPlatformTrailingSlash.config.method') === 'redirect';
  60.     }
  61.     private function getStatusCode(): int
  62.     {
  63.         return $this->systemConfigService->getInt('KielCodingPlatformTrailingSlash.config.redirectCode') ?: 301;
  64.     }
  65. }