<?php
namespace App\EventListener;
use App\Entity\User;
use App\Entity\UserProject;
use App\Service\ZpriceHelper;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserEventListener implements EventSubscriberInterface
{
private ZpriceHelper $zPriceHelper;
private EntityManagerInterface $manager;
public function __construct(ZpriceHelper $zPriceHelper, EntityManagerInterface $manager)
{
$this->zPriceHelper = $zPriceHelper;
$this->manager = $manager;
}
public static function getSubscribedEvents(): array
{
return [
AfterEntityPersistedEvent::class => 'onUserPersisted',
];
}
/**
* @throws JWTDecodeFailureException
*/
public function onUserPersisted(AfterEntityPersistedEvent $event): void
{
$entity = $event->getEntityInstance();
if ($entity instanceof User) {
$currentProject = $this->zPriceHelper->getCurrentProject();
if ($currentProject) {
$up = new UserProject($entity, $currentProject, $entity->getRoles());
$this->manager->persist($up);
$entity->addUserProject($up);
$this->manager->flush();
}
}
}
}