<?php
declare(strict_types=1);
namespace App\EventsSubscriber\System;
use App\Contracts\System\OnlyGuestController;
use App\Contracts\User\Role;
use App\Entity\User;
use App\Services\Creator\Exception\AuthException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class KernelEventsSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => [
'onController',
],
];
}
public function __construct(
private readonly Security $security,
private readonly UrlGeneratorInterface $urlGenerator,
) {
}
public function onController(ControllerEvent $event): void
{
/** @var User|null $user */
$user = $this->security->getUser();
$controller = $event->getController();
if (!is_array($controller) || $user === null) {
return;
}
if ($user->isBlocked() || $user->isDeleted()) {
throw new AuthException('You were removed from the platform', 403);
}
if ($controller[0] instanceof OnlyGuestController) {
$route = $this->security->isGranted(Role::CREATOR)
? 'creator-activity'
: 'sponsor-campaign-list';
$event->setController(function () use ($route) {
return new RedirectResponse($this->urlGenerator->generate($route));
});
}
}
}