Skip to content

Instantly share code, notes, and snippets.

@ducho
Created June 20, 2023 18:06
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/a543b09914eb640ef588161ab714f441 to your computer and use it in GitHub Desktop.
Save ducho/a543b09914eb640ef588161ab714f441 to your computer and use it in GitHub Desktop.
EntityEventSubscriber
<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
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;
public function __construct(LoggerInterface $dbLogger)
{
$this->logger = $dbLogger;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preRemove,
Events::preUpdate,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->logActivity(Events::postPersist, $args);
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->logActivity(Events::preRemove, $args);
}
public function preUpdate(PreUpdateEventArgs $args): void
{
if (self::isEnabled() && $args->getObject() instanceof LoggableEntityInterface) {
$changeSet = $args->getEntityChangeSet();
if ($changeSet) {
$this->logger->info(Events::preUpdate, [
'entity' => $args->getEntity(),
'args' => $args,
]);
}
}
}
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): void
{
if (self::isEnabled() && $args->getObject() instanceof LoggableEntityInterface) {
$this->logger->info($action, [
'entity' => $args->getObject(),
'args' => $args,
]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment