src/Service/SuperAdmin/EventListener/UserActionLogListener.php line 55

Open in your IDE?
  1. <?php
  2. namespace Harmonizely\Service\SuperAdmin\EventListener;
  3. use Harmonizely\Core\Exception\UnexpectedException;
  4. use Harmonizely\Core\Security\Contract\ISuperAdminSecurityHelper;
  5. use Harmonizely\Entity\SuperAdmin\UserActionLogEntity;
  6. use Harmonizely\Entity\SuperAdmin\UserEntity;
  7. use Harmonizely\Repository\SuperAdmin\Contract\IUserActionLogRepository;
  8. use Harmonizely\Service\SuperAdmin\Event\UserActionEvent;
  9. use Symfony\Component\HttpFoundation\RequestStack;
  10. class UserActionLogListener
  11. {
  12.     /**
  13.      * @var ISuperAdminSecurityHelper
  14.      */
  15.     private ISuperAdminSecurityHelper $security;
  16.     /**
  17.      * @var IUserActionLogRepository
  18.      */
  19.     private IUserActionLogRepository $repository;
  20.     /**
  21.      * @var RequestStack
  22.      */
  23.     private RequestStack $requestStack;
  24.     /**
  25.      * UserActionLogListener constructor.
  26.      *
  27.      * @param ISuperAdminSecurityHelper $security
  28.      * @param IUserActionLogRepository $repository
  29.      * @param RequestStack $requestStack
  30.      */
  31.     public function __construct(
  32.         ISuperAdminSecurityHelper $security,
  33.         IUserActionLogRepository $repository,
  34.         RequestStack $requestStack
  35.     )
  36.     {
  37.         $this->security $security;
  38.         $this->repository $repository;
  39.         $this->requestStack $requestStack;
  40.     }
  41.     /**
  42.      * Handle user action
  43.      *
  44.      * @param UserActionEvent $event
  45.      * @throws UnexpectedException
  46.      */
  47.     public function onAction(UserActionEvent $event): void
  48.     {
  49.         $user $this->security->getUser();
  50.         if ($user instanceof UserEntity) {
  51.             $request $this->requestStack->getCurrentRequest();
  52.             $ip 'undefined';
  53.             if ($request && $request->getClientIp()) {
  54.                 $ip $request->getClientIp();
  55.             }
  56.             $this->repository->addLog(new UserActionLogEntity(
  57.                 $event->getActionType(),
  58.                 $event->getObjectType(),
  59.                 $event->getObjectId(),
  60.                 $ip$user
  61.             ));
  62.         } else {
  63.             throw new UnexpectedException('Invalid user type performed action'500);
  64.         }
  65.     }
  66. }