<?php
declare(strict_types=1);
namespace App\Presentation\Web\FrontOffice\Project\Event\Listener;
use App\Presentation\Web\FrontOffice\Common\Context;
use App\Presentation\Web\FrontOffice\Common\Controller\AbstractFrontOfficeController;
use App\Presentation\Web\FrontOffice\Project\Controller\CreateProjectAction;
use App\Presentation\Web\FrontOffice\Project\Controller\SwitchDataSourceAction;
use App\Presentation\Web\FrontOffice\User\Controller\UpdateUserAction;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Handles situation when context project is not set, but the requested page is supposed to be loaded with project data.
*/
final class HandleRequestWithNoProject
{
private $urlGenerator;
private $context;
public function __construct(
UrlGeneratorInterface $urlGenerator,
Context $context
) {
$this->urlGenerator = $urlGenerator;
$this->context = $context;
}
/**
* Listens for kernel.request event.
*
* @param RequestEvent $requestEvent
*/
public function onKernelRequest(RequestEvent $requestEvent)
{
$this->handleNoProject($requestEvent);
}
/**
* Redirects to create project if no active project is found.
*
* @param RequestEvent $requestEvent
*/
private function handleNoProject(RequestEvent $requestEvent)
{
$request = $requestEvent->getRequest();
$controller = $request->attributes->get('_controller');
$allowedControllers = [UpdateUserAction::class, CreateProjectAction::class, SwitchDataSourceAction::class];
if (Request::METHOD_GET === $request->getMethod() &&
!in_array($controller, $allowedControllers) &&
is_subclass_of($controller, AbstractFrontOfficeController::class) &&
!$this->context->getProjectId()
) {
$session = $request->getSession();
$session->getFlashBag()->add('info', 'Create a project to proceed');
$requestEvent->setResponse(
new RedirectResponse($this->urlGenerator->generate('create_project'))
);
}
}
}