Skip to content

Instantly share code, notes, and snippets.

@ger86
Created February 8, 2019 13:44
Show Gist options
  • Save ger86/24d88309fd224c511df474ab0b1a1c14 to your computer and use it in GitHub Desktop.
Save ger86/24d88309fd224c511df474ab0b1a1c14 to your computer and use it in GitHub Desktop.
<?php
namespace App\Doctrine\EntityListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use App\Entity\Post;
class PostEntityListener {
/**
* @inheritDoc
* @param OnFlushEventArgs $event
* @return void
*/
public function onFlush(OnFlushEventArgs $event) {
$em = $event->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledCollectionUpdates() as $collection) {
$entity = $collection->getOwner();
if ($entity instanceof Post) {
foreach ($collection->getDeleteDiff() as $itemDeleted) {
if ($itemDeleted instanceof Comment) {
$historyRecord = new HistoryRecord($entity, $itemDeleted, 'remove');
$em->persist($historyRecord);
$uow->computeChangeSet($em->getClassMetadata(get_class($historyRecord)), $historyRecord);
}
}
foreach ($collection->getInsertDiff() as $itemInserted) {
if ($itemInserted instanceof Comment) {
$historyRecord = new HistoryRecord($entity, $itemInserted, 'inserted');
$em->persist($historyRecord);
$uow->computeChangeSet($em->getClassMetadata(get_class($historyRecord)), $historyRecord);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment