Skip to content

Instantly share code, notes, and snippets.

@blar
Created February 20, 2011 14:55
Show Gist options
  • Save blar/836026 to your computer and use it in GitHub Desktop.
Save blar/836026 to your computer and use it in GitHub Desktop.
<?php
namespace Blar;
use Doctrine\Common\EventSubscriber,
Doctrine\ORM\Events,
Doctrine\ORM\Event\OnFlushEventArgs,
Doctrine\ORM\EntityManager;
class AuditListener implements EventSubscriber {
public function getSubscribedEvents() {
return array(Events::onFlush);
}
public function onFlush(OnFlushEventArgs $args) {
$entityManager = $args->getEntityManager();
$eventManager = $entityManager->getEventManager();
// Remove event
$eventManager->removeEventListener('onFlush', $this);
$unitOfWork = $entityManager->getUnitOfWork();
foreach($unitOfWork->getScheduledEntityUpdates() as $key => $entity) {
if($entity instanceOf \Blar\Model\Audit) {
continue;
}
if($entity instanceOf \Blar\Model\Audit\Property) {
continue;
}
$changeSet = $unitOfWork->getEntityChangeSet($entity);
$audit = new \Blar\Model\Audit();
$audit->setEntity($entity);
foreach ($changeSet AS $field => $values) {
list($oldValue, $newValue) = $values;
if(!is_scalar($oldValue)) {
continue;
}
if(!is_scalar($newValue)) {
continue;
}
$property = new \Blar\Model\Audit\Property();
$property->setName($field);
$property->setOld($oldValue);
$property->setNew($newValue);
$property->setAudit($audit);
$audit->getProperties()->add($property);
$entityManager->persist($property);
}
$audit->save();
}
// Add previous removed event
$eventManager->addEventListener($this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment