<?php
declare(strict_types=1);
namespace App\Bundles\AuditBundle\EventListener;
use App\Bundles\AuditBundle\Event\ExportEvent;
use App\Bundles\AuditBundle\Factory\AuditLogEntryFactory;
use App\Bundles\OrganizationBundle\Entity\Organization;
use App\Bundles\OrganizationBundle\Exception\UserOrganizationNotFoundException;
use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationProvider;
use App\Bundles\UserBundle\Entity\User;
use App\Bundles\UserBundle\Service\User\UserProvider;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class ExportEventListener implements EventSubscriberInterface
{
public function __construct(
private readonly UserProvider $userProvider,
private readonly AuditLogEntryFactory $factory,
private readonly EntityManagerInterface $entityManager,
private readonly UserOrganizationProvider $userOrganizationProvider,
) {
}
public static function getSubscribedEvents(): array
{
return [
ExportEvent::class => 'onExport',
];
}
public function onExport(ExportEvent $event): void
{
/** @var User|null $user */
$user = $this->userProvider->provideFromSession();
$organization = $this->getOrganization();
if (!$user || !$organization) {
return;
}
$entry = $this->factory->createExport($user, $organization, $event->getClassName());
$this->entityManager->persist($entry);
$this->entityManager->flush();
}
private function getOrganization(): ?Organization
{
try {
return $this->userOrganizationProvider->provideFromSession()->getOrganization();
} catch (UserOrganizationNotFoundException) {
return null;
}
}
}