Created
June 20, 2023 18:06
-
-
Save ducho/a543b09914eb640ef588161ab714f441 to your computer and use it in GitHub Desktop.
EntityEventSubscriber
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 | |
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