<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CityRedirectSubscriber implements EventSubscriberInterface
{
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
$host = $request->getHost();
$path = $request->getPathInfo();
// Try to match the first path segment as the city slug
if (preg_match('#^/([^/]+)(?:/([^/]+))?#', $path, $m)) {
$city = strtolower($m[1]);
$second = isset($m[2]) ? strtolower($m[2]) : '';
// Cities that moved to ocmax.sk
$movedCities = ['dunajskastreda', 'zilina'];
if (in_array($city, $movedCities, true)) {
// Do not redirect admin or auth paths to avoid breaking back office
$excluded = ['admin', 'login', 'logout'];
if (in_array($second, $excluded, true)) {
return;
}
// If we're not already on ocmax.sk, redirect there preserving the URI
if ($host !== 'ocmax.sk' && $host !== 'www.ocmax.sk') {
$target = 'https://ocmax.sk' . $request->getRequestUri();
$event->setResponse(new RedirectResponse($target, 301));
}
}
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 0],
];
}
}