Skip to content

Instantly share code, notes, and snippets.

@ducho
Created June 20, 2023 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducho/25a85896ea2a45ca8474ebea33617cf4 to your computer and use it in GitHub Desktop.
Save ducho/25a85896ea2a45ca8474ebea33617cf4 to your computer and use it in GitHub Desktop.
Working subscriber
<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Psr\Log\LoggerInterface;
use Satur\DatabaseBundle\Doctrine\Interface\LoggableEntityInterface;
class EntityEventSubscriber implements EventSubscriberInterface
{
private LoggerInterface $logger;
private static bool $enabled = true;
private static bool $logCreate = true;
private static bool $logUpdate = true;
private static bool $logDelete = true;
public function __construct(LoggerInterface $dbLogger)
{
$this->logger = $dbLogger;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::prePersist,
Events::preRemove,
Events::postRemove,
Events::preUpdate,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->logActivity(Events::postPersist, $args);
}
public function prePersist(LifecycleEventArgs $args): void
{
$this->logActivity(Events::prePersist, $args);
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->logActivity(Events::preRemove, $args);
}
public function postRemove(LifecycleEventArgs $args): void
{
$this->logActivity(Events::postRemove, $args);
}
public function preUpdate(PreUpdateEventArgs $args): void
{
$changeSet = $args->getEntityChangeSet();
if ($changeSet) {
$this->logActivity(Events::preUpdate, $args, $changeSet);
}
}
public static function setEnabled(bool $enabled): void
{
self::$enabled = $enabled;
}
public static function isEnabled(): bool
{
return self::$enabled;
}
private function logActivity(string $action, LifecycleEventArgs $args, mixed $context = null): void
{
if (self::isEnabled() && $args->getObject() instanceof LoggableEntityInterface) {
$this->logger->info($action, [
'entity' => $args->getObject(),
'context' => $context,
]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment