<?php
namespace App\EventSubscriber;
use App\Repository\UserRepository;
use SimpleThings\EntityAudit\AuditManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class AuditEntryListenerSubscriber implements EventSubscriberInterface
{
private $userRepository;
private $auditManager;
public function __construct(UserRepository $userRepository, AuditManager $auditManager)
{
$this->userRepository = $userRepository;
$this->auditManager = $auditManager;
}
public function onKernelController(ControllerEvent $event)
{
$request = $event->getRequest();
// Get the currently authenticated user's email based on the API token
$apiToken = $this->getApiTokenFromRequest($request);
if($apiToken){
$currentUser = $this->userRepository->findOneBy(['apiKey' => $apiToken]);
if ($currentUser) {
$email = $currentUser->email();
$auditEntry = $this->auditManager->getConfiguration(); // Get the current audit entry being created.
$auditEntry->setUsernameCallable(function() use ($email) {
return $email;
});
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
private function getApiTokenFromRequest(Request $request)
{
return $request->headers->get('x-auth-token');
}
}