src/EventSubscriber/CityRedirectSubscriber.php line 12

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\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class CityRedirectSubscriber implements EventSubscriberInterface
  8. {
  9.     public function onKernelRequest(RequestEvent $event): void
  10.     {
  11.         if (!$event->isMainRequest()) {
  12.             return;
  13.         }
  14.         $request $event->getRequest();
  15.         $host $request->getHost();
  16.         $path $request->getPathInfo();
  17.         // Try to match the first path segment as the city slug
  18.         if (preg_match('#^/([^/]+)(?:/([^/]+))?#'$path$m)) {
  19.             $city strtolower($m[1]);
  20.             $second = isset($m[2]) ? strtolower($m[2]) : '';
  21.             // Cities that moved to ocmax.sk
  22.             $movedCities = ['dunajskastreda''zilina'];
  23.             if (in_array($city$movedCitiestrue)) {
  24.                 // Do not redirect admin or auth paths to avoid breaking back office
  25.                 $excluded = ['admin''login''logout'];
  26.                 if (in_array($second$excludedtrue)) {
  27.                     return;
  28.                 }
  29.                 // If we're not already on ocmax.sk, redirect there preserving the URI
  30.                 if ($host !== 'ocmax.sk' && $host !== 'www.ocmax.sk') {
  31.                     $target 'https://ocmax.sk' $request->getRequestUri();
  32.                     $event->setResponse(new RedirectResponse($target301));
  33.                 }
  34.             }
  35.         }
  36.     }
  37.     public static function getSubscribedEvents(): array
  38.     {
  39.         return [
  40.             KernelEvents::REQUEST => ['onKernelRequest'0],
  41.         ];
  42.     }
  43. }