<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
class NormalizeUrlSubscriber implements EventSubscriberInterface
{
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$uri = $request->getRequestUri();
$normalizedUri = preg_replace('#/+#', '/', $uri);
if ($uri !== $normalizedUri) {
$event->setResponse(
new RedirectResponse(
$normalizedUri,
Response::HTTP_MOVED_PERMANENTLY
)
);
}
}
public static function getSubscribedEvents()
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}