<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Repository\CompanyRepository;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class RequestListener
{
private $tokenStorage;
private $entityManagerInterface;
private $companyRepository;
private ParameterBagInterface $parameter;
public function __construct(TokenStorageInterface $tokenStorageInterface, EntityManagerInterface $entityManagerInterface, ParameterBagInterface $parameterBag,CompanyRepository $companyRepository)
{
$this->tokenStorage = $tokenStorageInterface;
$this->entityManagerInterface = $entityManagerInterface;
$this->parameter = $parameterBag;
$this->companyRepository = $companyRepository;
}
public function onKernelRequest(RequestEvent $requestEvent)
{
//get domain_name
$request = $requestEvent->getRequest();
$host = $request->getHost();
$company = $this->companyRepository->findByDomaineNameHost($host)
;
if (!empty($company)) {
// set company domain name
$request->attributes->set('agency_connect', ['id'=>$company->getId(),'logo'=>$company->getLogoName()]);
}
//end
if ($this->tokenStorage->getToken()) {
$user = $this->tokenStorage->getToken()->getUser();
if ($user instanceof UserInterface) {
if (!$this->entityManagerInterface->isOpen()) {
$this->entityManagerInterface = $this->entityManagerInterface->create(
$this->entityManagerInterface->getConnection(),
$this->entityManagerInterface->getConfiguration()
);
}
$user->setLastActivityAt(new \DateTimeImmutable());
$user->setAutorizationDateAt(new \DateTimeImmutable());
$this->entityManagerInterface->flush();
}
if(in_array('ROLE_AUTHOR', $user->getRoles()) || in_array('ROLE_EDITOR', $user->getRoles())){
$response = new RedirectResponse("{$this->parameter->get('front_website_url')}/wp-admin");
$requestEvent->setResponse($response);
}
}
}
}