<?php
namespace App\EventSubscriber;
use App\Entity\WithQRCodeInterface;
use App\Service\QRCodeService;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class QRCodeGenerator implements EventSubscriberInterface
{
public function __construct(
private QRCodeService $qrCodeService,
)
{
}
public static function getSubscribedEvents()
{
return [
AfterEntityPersistedEvent::class => [
['onAfterEntityPersisted', -1]
],
AfterEntityUpdatedEvent::class => [
['onAfterEntityUpdated', -1]
],
AfterEntityDeletedEvent::class => [
['onAfterEntityDeleted', -1]
],
];
}
/**
* @throws Exception
*/
public function onAfterEntityPersisted(AfterEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof WithQRCodeInterface) {
$this->qrCodeService->generateForEntity($entity);
}
}
/**
* @throws Exception
*/
public function onAfterEntityUpdated(AfterEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof WithQRCodeInterface) {
$this->qrCodeService->generateForEntity($entity);
}
}
public function onAfterEntityDeleted(AfterEntityDeletedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof WithQRCodeInterface) {
// unlinking the qr code file
$this->qrCodeService->unlinkQRCode($entity);
}
}
}