In a Symfony 3 project I have an entity that I want to audit the changes in some of the properties, so I though I could create an Event Listener to store them.
More or less the entity is as follows:
- ReceivedEmail: agent and caseDetail are the properties I want to audit
- ReceivedEmailChange: previousAgent, currentAgent and previousCaseDetail and currentCaseDetail
And the EventListener looks as follows
/**
* @param OnFlushEventArgs $args
*/
public function onFlush(OnFlushEventArgs $args)
{
/** @var ReceivedEmail $entity */
$entityManager = $args->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
$updates = $unitOfWork->getScheduledEntityUpdates();
foreach ($updates as $entity) {
if ($entity instanceof ReceivedEmail) {
$changes = $unitOfWork->getEntityChangeSet($entity);
$this->receivedEmailChanges[] = $this->receivedEmailChangeManager
->getReceivedEmailChanges($entity, $changes);
}
}
}
public function postFlush(PostFlushEventArgs $args)
{
$em = $args->getEntityManager();
$i = 0;
foreach($this->receivedEmailChanges as $receivedEmailChange) {
$em->persist($receivedEmailChange);
unset($this->receivedEmailChanges[$i]);
$i++;
}
if ($i > 0) {
$em->flush();
}
}
The problem is calling $entityManager->flush() on the postFlush method ends up in an infinte loop and on this error:
PHP Fatal error: Maximum function nesting level of '256' reached, aborting! in /var/www/sellbytel/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php on line 187
So my question is: how can I save the changes in the database from the EventListener if it is even possible? If not, is there a workaround to create this log?
onFlush
event to define an array of changes you need to process and than after processing these changes inpostFlush
starting the whole process again. Instead of relying on the unitOfWork you can try to replace the onFlush listener by manually saving old and new values using thepreUpdate
andpostUpdate
events instead. – lordrhodos