Last active
August 11, 2021 03:59
-
-
Save steveclifton/eb5705c3f19e1b29f8ba11cbe9a5d402 to your computer and use it in GitHub Desktop.
FooListener Example
This file contains 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 AppBundle\EventListener; | |
use AppBundle\Entity\FooHistory; | |
use Doctrine\ORM\Event\PreUpdateEventArgs; | |
class FooListener | |
{ | |
protected $entityManager; | |
public function __construct($entityManager) | |
{ | |
$this->entityManager = $entityManager; | |
} | |
public function preUpdate(Foo $foo, PreUpdateEventArgs $event): void | |
{ | |
// Some custom repository method to get a fooHistory for today | |
$fooHistory = $this->entityManager->getRepository(FooHistory::class) | |
->findOneForToday($foo->getId()); | |
// If it doesnt exist - create | |
if (!$fooHistory) { | |
$fooHistory = new FooHistory(); | |
$fooHistory->setFooId($foo->getId()); | |
$fooHistory->setDate(new \DateTime()); | |
} | |
// gethanges() just returns the json_encoded data into a php-assoc array | |
$existingHistory = $fooHistory->getChanges() ? $fooHistory->getChangesDecoded() : []; | |
// Loop over the change set for this listing | |
foreach ($event->getEntityChangeSet() as $field => $changes) { | |
$fromValue = ($existingHistory[$field]['fromValue'] ?? $event->getOldValue($field)); | |
$toValue = $event->getNewValue($field); | |
$update = [ | |
$field => [ | |
'fromValue' => $fromValue, | |
'toValue' => $toValue | |
] | |
]; | |
// Merge the history with the existing history - if it exists | |
$existingHistory = array_merge($existingHistory, $update); | |
$fooHistory->setChanges(json_encode($existingHistory)); | |
} | |
// Only queue up to be saved if it has a change history | |
$this->fooHistory = $fooHistory->getChanges() ? $fooHistory : null; | |
} | |
/** | |
* Write the fooHistory to the DB | |
*/ | |
public function postUpdate() | |
{ | |
// If we have something to persist, do it | |
if ($this->fooHistory) { | |
$this->entityManager->persist($this->fooHistory); | |
$this->entityManager->flush(); | |
} | |
$this->fooHistory = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment