src/EventSubscriber/LowercaseRedirectSubscriber.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. class LowercaseRedirectSubscriber implements EventSubscriberInterface
  8. {
  9.     private const BLACKLIST_REGEX = [
  10.         '/^\/wp-/'// Wordpress naked URLs
  11.         '/^\/edition\//'// WPSY-wrapped Wordpress URLs
  12.         '/^\/_wdt/'// Symfony web toolbar
  13.         '/^\/_profiler/'// Symfony profiler
  14.     ];
  15.     public function onKernelRequest(RequestEvent $event): void
  16.     {
  17.         $request $event->getRequest();
  18.         $path $request->getPathInfo();
  19.         // Check for blacklisted URLs. If matches, return.
  20.         foreach (self::BLACKLIST_REGEX as $regex) {
  21.             if (preg_match($regex$path)) {
  22.                 return;
  23.             }
  24.         }
  25.         // Check for uppercase characters in path. Otherwise, return.
  26.         if (!preg_match('/[A-Z]/'$path)) {
  27.             return;
  28.         }
  29.         // Redirect to lowercase version
  30.         $url $request->getSchemeAndHttpHost().$request->getBaseUrl().mb_strtolower($request->getPathInfo());
  31.         if (null !== $qs $request->getQueryString()) {
  32.             $url .= '?'.$qs;
  33.         }
  34.         $event->setResponse(
  35.             new RedirectResponse(
  36.                 $url,
  37.                 Response::HTTP_MOVED_PERMANENTLY
  38.             )
  39.         );
  40.     }
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return [
  44.             'kernel.request' => 'onKernelRequest',
  45.         ];
  46.     }
  47. }