<?php
namespace App\Listener;
use App\Entity\User;
use App\Helpers\ApiLogger;
use App\Services\ActionLogService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* Class ApiLoggerListener
* @package App\Listener
*/
class WebLoggerListener
{
/**
* @var TokenStorageInterface
*/
private TokenStorageInterface $tokenStorage;
/**
* @var ActionLogService
*/
private ActionLogService $actionLogManager;
/**
* @param TokenStorageInterface $tokenStorage
* @param ActionLogService $actionLogManager
*/
public function __construct(
TokenStorageInterface $tokenStorage,
ActionLogService $actionLogManager
) {
$this->tokenStorage = $tokenStorage;
$this->actionLogManager = $actionLogManager;
}
/**
* @param ControllerEvent $event
* @return void
*/
public function onKernelController(ControllerEvent $event): void
{
$token = $this->tokenStorage->getToken();
/** @var User|null $user */
$user = null;
if ($token instanceof UsernamePasswordToken) {
/** @var User $user */
$user = $token->getUser();
}
$controller = $event->getController();
if (!is_object($controller) && $controller[0] instanceof AbstractController) {
$request = $event->getRequest();
$rawContent = $request->getContent();
$content = json_decode($rawContent, true);
if (is_null($content)) {
parse_str($request->getContent(), $parsed);
if (!empty($parsed)) {
$content = json_decode(json_encode($parsed), true);
}
}
ApiLogger::encryptPassword($content);
$this->actionLogManager->create($user, $request, $content);
}
}
}