<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Helper\Image\ImageInterface;
use App\Repository\Franchise\DomainRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class LocalSubscriber implements EventSubscriberInterface
{
public function __construct(
private string $mainUrl,
private DomainRepository $domainRepository,
) {
}
public static function getSubscribedEvents()
{
return [KernelEvents::REQUEST => [['onKernelRequest', 20]]];
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$locale = $request->getSession()->get('_locale');
$host = $request->server->get('HTTP_HOST');
if (null !== $locale && '' !== trim($locale)) {
$request->attributes->set('_locale', $locale);
}
if (ImageInterface::IMAGE_CROP_PATH_ROUTE_NAME === $request->get('_route')
&& false === str_ends_with($host, $this->mainUrl)
&& false === $this->domainRepository->exist($host)
) {
throw new UnauthorizedHttpException(Response::$statusTexts[Response::HTTP_UNAUTHORIZED]);
}
}
}