<?php
/**
* @copyright Copyright (c) 2022 Biceps
*/
namespace Biceps\DocumentBundle\EventListener;
use Biceps\DocumentBundle\Controller\ListController;
use Biceps\DocumentBundle\Controller\SecurityController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Routing\RouterInterface;
class SessionLockListener
{
/**
* @var RouterInterface
*/
protected RouterInterface $router;
/**
* @var int
*/
protected int $time;
/**
* ControllerListener constructor.
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
$this->time = time();
}
/**
* @param ControllerEvent $event
*/
public function onKernelController(ControllerEvent $event): void
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
$route = $event->getRequest()->get('_route');
$session = $event->getRequest()->getSession();
$lock = $session->get('lock', false);
if (
$event->isMainRequest() &&
!$this->isBlacklistedController($controller) &&
!$this->isBlacklistedRoute($route) &&
($this->sessionShouldBeLocked($session) || $lock)
) {
if (!$lock) {
$session->set('lock', $route);
}
$redirectUrl = $this->router->generate('lock');
$event->setController(function () use ($redirectUrl) {
return new RedirectResponse($redirectUrl);
});
}
$session->set('lastActivity', $this->time);
}
/**
* @param SessionInterface $session
*
* @return bool
*/
protected function sessionShouldBeLocked(SessionInterface $session) : bool
{
return $this->time - $session->get('lastActivity', 0) > 1200;
}
/**
* @param array $controller
*
* @return bool
*/
protected function isBlacklistedController(array $controller) : bool
{
return $controller[0] instanceof ListController ||
$controller[0] instanceof SecurityController;
}
/**
* @param $route
*
* @return bool
*/
protected function isBlacklistedRoute($route) : bool
{
if (preg_match('#^(_.*|document-preview|document-download)$#', $route)) {
return true;
}
return false;
}
}