Created
February 20, 2011 14:55
-
-
Save blar/836026 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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