<?php declare(strict_types=1);
namespace KielCodingPlatformTrailingSlash\TrailingSlash;
use Shopware\Core\SalesChannelRequest;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestSubscriber implements EventSubscriberInterface
{
private const ROUTE_NAME = 'frontend.navigation.page';
private SystemConfigService $systemConfigService;
public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onRequest'],
],
];
}
public function onRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if (!$event->isMainRequest()) {
return;
}
if (!$this->isNavigationRequest($request)) {
return;
}
if (!$this->shouldRedirect()) {
return;
}
if (!$request->attributes->has(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK)) {
return;
}
$canonical = $request->attributes->get(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK);
$current = $request->attributes->get(RequestTransformer::ATTRIBUTE_CURRENT_LINK);
if ($canonical === $current) {
// no redirect needed
return;
}
if ($request->getQueryString()) {
$canonical .= '?' . $request->getQueryString();
}
$statusCode = $this->getStatusCode();
$event->setResponse(new RedirectResponse($canonical, $statusCode));
}
private function isNavigationRequest(Request $request): bool
{
return $request->attributes->get('_route') == self::ROUTE_NAME;
}
private function shouldRedirect(): bool
{
return $this->systemConfigService->getString('KielCodingPlatformTrailingSlash.config.method') === 'redirect';
}
private function getStatusCode(): int
{
return $this->systemConfigService->getInt('KielCodingPlatformTrailingSlash.config.redirectCode') ?: 301;
}
}