<?php
namespace Harmonizely\Service\SuperAdmin\EventListener;
use Harmonizely\Core\Exception\UnexpectedException;
use Harmonizely\Core\Security\Contract\ISuperAdminSecurityHelper;
use Harmonizely\Entity\SuperAdmin\UserActionLogEntity;
use Harmonizely\Entity\SuperAdmin\UserEntity;
use Harmonizely\Repository\SuperAdmin\Contract\IUserActionLogRepository;
use Harmonizely\Service\SuperAdmin\Event\UserActionEvent;
use Symfony\Component\HttpFoundation\RequestStack;
class UserActionLogListener
{
/**
* @var ISuperAdminSecurityHelper
*/
private ISuperAdminSecurityHelper $security;
/**
* @var IUserActionLogRepository
*/
private IUserActionLogRepository $repository;
/**
* @var RequestStack
*/
private RequestStack $requestStack;
/**
* UserActionLogListener constructor.
*
* @param ISuperAdminSecurityHelper $security
* @param IUserActionLogRepository $repository
* @param RequestStack $requestStack
*/
public function __construct(
ISuperAdminSecurityHelper $security,
IUserActionLogRepository $repository,
RequestStack $requestStack
)
{
$this->security = $security;
$this->repository = $repository;
$this->requestStack = $requestStack;
}
/**
* Handle user action
*
* @param UserActionEvent $event
* @throws UnexpectedException
*/
public function onAction(UserActionEvent $event): void
{
$user = $this->security->getUser();
if ($user instanceof UserEntity) {
$request = $this->requestStack->getCurrentRequest();
$ip = 'undefined';
if ($request && $request->getClientIp()) {
$ip = $request->getClientIp();
}
$this->repository->addLog(new UserActionLogEntity(
$event->getActionType(),
$event->getObjectType(),
$event->getObjectId(),
$ip, $user
));
} else {
throw new UnexpectedException('Invalid user type performed action', 500);
}
}
}