src/EventSubscriber/AuditEntryListenerSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\UserRepository;
  4. use SimpleThings\EntityAudit\AuditManager;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class AuditEntryListenerSubscriber implements EventSubscriberInterface
  10. {
  11.     private $userRepository;
  12.     private $auditManager;
  13.     public function __construct(UserRepository $userRepositoryAuditManager $auditManager)
  14.     {
  15.         $this->userRepository $userRepository;
  16.         $this->auditManager $auditManager;
  17.     }
  18.     public function onKernelController(ControllerEvent $event)
  19.     {
  20.         $request $event->getRequest();
  21.         // Get the currently authenticated user's email based on the API token
  22.         $apiToken $this->getApiTokenFromRequest($request);
  23.         if($apiToken){
  24.             $currentUser $this->userRepository->findOneBy(['apiKey' => $apiToken]);
  25.     
  26.             if ($currentUser) {
  27.                 $email $currentUser->email();
  28.     
  29.                 $auditEntry $this->auditManager->getConfiguration(); // Get the current audit entry being created.
  30.                 $auditEntry->setUsernameCallable(function() use ($email) {
  31.                     return $email;
  32.                 });
  33.             }
  34.         }
  35.     }
  36.     public static function getSubscribedEvents()
  37.     {
  38.         return [
  39.             KernelEvents::CONTROLLER => 'onKernelController',
  40.         ];
  41.     }
  42.     private function getApiTokenFromRequest(Request $request)
  43.     {
  44.         return $request->headers->get('x-auth-token');
  45.     }
  46. }