src/EventListener/LoggingListener.php line 64

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Loggable;
  4. use App\Helper\LoggingHelper;
  5. use App\Message\LoggingMessage;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Doctrine\ORM\Event\LifecycleEventArgs;
  8. use Symfony\Component\Messenger\MessageBusInterface;
  9. use Symfony\Component\Security\Core\Security;
  10. final class LoggingListener
  11. {
  12.     private EntityManagerInterface $entityManager;
  13.     private MessageBusInterface $bus;
  14.     private Security $security;
  15.     /**
  16.      * @param EntityManagerInterface $entityManager
  17.      * @param MessageBusInterface $bus
  18.      * @param Security $security
  19.      */
  20.     public function __construct(
  21.         EntityManagerInterface $entityManager,
  22.         MessageBusInterface $bus,
  23.         Security $security
  24.     ) {
  25.         $this->entityManager $entityManager;
  26.         $this->bus $bus;
  27.         $this->security $security;
  28.     }
  29.     /**
  30.      * @return void
  31.      */
  32.     public function postUpdate(LifecycleEventArgs $event): void
  33.     {
  34.         $entity $event->getObject();
  35.         if ($this->supports($entity)) {
  36.             $uow $this->entityManager->getUnitOfWork();
  37.             $uow->computeChangeSets();
  38.             $payloadAfter $uow->getOriginalEntityData($entity);
  39.             $payloadAfter  LoggingHelper::getCustomizedArray($payloadAfter$entity->getFields());
  40.             $changesSet $uow->getEntityChangeSet($entity);
  41.             $className get_class($entity);
  42.             $payloadBefore = [];
  43.             foreach ($changesSet as $key => $changeset) {
  44.                 $payloadBefore[$key] = $changeset[0];
  45.             }
  46.             $payloadBefore  array_merge($payloadAfter$payloadBefore);
  47.             if (array_intersect_key($entity->getFields(), $changesSet)) {
  48.                 $this->bus->dispatch(new LoggingMessage(
  49.                     $className,
  50.                     $this->security->getUser() ? $this->security->getUser()->getId() : -1,
  51.                     $changesSet,
  52.                     LoggingHelper::fillCollectionById($payloadBefore),
  53.                     LoggingHelper::fillCollectionById($payloadAfter),
  54.                     $entity->getId(),
  55.                     new \DateTimeImmutable('now')
  56.                 ));
  57.             }
  58.         }
  59.     }
  60.     /**
  61.      * @param $entity
  62.      *
  63.      * @return bool
  64.      */
  65.     private function supports($entity): bool
  66.     {
  67.         return $entity instanceof Loggable;
  68.     }
  69. }