<?php
declare(strict_types=1);
namespace Harmonizely\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Harmonizely\Model\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class CurrentUserSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $entityManager;
private const ROUTES_IGNORE_THIS_FILTER = [
'panel.api.event_type.list',
'panel.api.poll.create',
'panel.api.poll.list',
'panel.api.availability_rule',
'panel.api.poll.get',
'panel.api.event.edit',
'panel.api.event.no_show.list',
'panel.api.chart.list_status',
'panel.api.calendar_integration.calendar_account.list',
'panel.api.calendar_integration.calendar.default',
'panel.api.event.resend_notification',
'hrm_routing_form_index',
'api_organization_delete_member',
'panel.api.organization.leave',
'panel.organization.delete',
'api_organization_members_list',
'panel.api.zapier.event.mock',
'panel.api.routing_form.field.delete',
'panel.api.routing_form.create',
'panel.api.routing_form.field.create',
'panel.api.routing_form.route.create',
'panel.api.routing_form.delete',
'panel.api.routing_form.route.delete',
'panel.api.routing_form.get',
'panel.api.routing_form.route.get',
'panel.api.routing_form.list',
'panel.api.routing_form_result.list',
'panel.api.routing_form.update',
'panel.api.routing_form.field.update',
'panel.api.routing_form.route.update',
];
public function __construct(EntityManagerInterface $entityManager, TokenStorageInterface $tokenStorage)
{
$this->entityManager = $entityManager;
$this->tokenStorage = $tokenStorage;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['setCurrentUser'],
];
}
public function setCurrentUser(RequestEvent $event)
{
if (!in_array($event->getRequest()->get('_route'), self::ROUTES_IGNORE_THIS_FILTER)) {
$token = $this->tokenStorage->getToken();
if ($token && $token->getUser() instanceof UserInterface) {
$this->entityManager
->getFilters()
->enable('current_user')
->setParameter('user_id', $token->getUser()->getId());
}
}
}
}