Skip to content

Commit

Permalink
Merge pull request #26 from whitedigital-eu/fix/original-entity-data
Browse files Browse the repository at this point in the history
fix: log entity changes better
  • Loading branch information
raraworks authored Apr 12, 2023
2 parents ad81352 + ec5f4c5 commit 86242d8
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/EventSubscriber/AuditDoctrineEventSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,20 @@ public function getSubscribedEvents(): array

public function postPersist(LifecycleEventArgs $args): void
{
$this->logActivity($this->translator->trans('entity.create', domain: 'Audit'), $args);
$this->logActivity(Events::postPersist, $this->translator->trans('entity.create', domain: 'Audit'), $args);
}

public function preRemove(LifecycleEventArgs $args): void
{
$this->logActivity($this->translator->trans('entity.remove', domain: 'Audit'), $args);
$this->logActivity(Events::preRemove, $this->translator->trans('entity.remove', domain: 'Audit'), $args);
}

public function postUpdate(LifecycleEventArgs $args): void
{
$this->logActivity($this->translator->trans('entity.update', domain: 'Audit'), $args);
$this->logActivity(Events::postUpdate, $this->translator->trans('entity.update', domain: 'Audit'), $args);
}

private function logActivity(string $action, LifecycleEventArgs $args): void
private function logActivity(string $event, string $action, LifecycleEventArgs $args): void
{
if (!$this->isEnabled) {
return;
Expand All @@ -69,11 +69,23 @@ private function logActivity(string $action, LifecycleEventArgs $args): void
}

$entityManager = $args->getObjectManager();
$originalEntityData = $entityManager->getUnitOfWork()->getEntityChangeSet($entity);
if (Events::postUpdate === $event) {
$originalEntityData = $entityManager->getUnitOfWork()->getEntityChangeSet($entity);
$entityData = [];
foreach ($originalEntityData as $field => $value) {
$entityData[$field] = [
$this->normalizeEntityCollections($value),
];
}
$originalEntityData = $entityData;
} else {
$originalEntityData = $entityManager->getUnitOfWork()->getOriginalEntityData($entity);
$originalEntityData = $this->normalizeEntityCollections($originalEntityData);
}

if (!array_key_exists('id', $originalEntityData)) {
$originalEntityData['id'] = $entity->getId();
}
$originalEntityData = $this->normalizeEntityCollections($originalEntityData);

$this->audit->audit(AuditType::DB, sprintf('%s on %s', $action, $entity::class), $originalEntityData);
}
Expand Down

0 comments on commit 86242d8

Please sign in to comment.