src/Core/Application/EventSubscriber/Chat/SetUserChatSubscriber.php line 41
<?phpdeclare(strict_types=1);namespace App\Core\Application\EventSubscriber\Chat;use App\Core\Application\Event\Chat\ChatUserPersonalTokenGeneratedEvent;use App\Core\Application\Event\Chat\SetUserChatEvent;use App\Core\Application\Service\RocketChat\RocketChatClientServiceInterface;use App\Core\Domain\Entity\ChatSetting\ChatSetting;use App\Core\Domain\Entity\ChatSetting\ChatUserInterface;use App\Core\Domain\Entity\Student\Student;use App\Core\Domain\Entity\User\User;use App\Core\Domain\Repository\ChatSetting\ChatChannelRepositoryInterface;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\Uid\Uuid;class SetUserChatSubscriber implements EventSubscriberInterface{private readonly EntityManagerInterface $em;private readonly RocketChatClientServiceInterface $rocketChatClientService;public function __construct(EntityManagerInterface $em,RocketChatClientServiceInterface $rocketChatClientService,private readonly ChatChannelRepositoryInterface $chatChannelRepository){$this->em = $em;$this->rocketChatClientService = $rocketChatClientService;}public static function getSubscribedEvents(): array{return [SetUserChatEvent::class => 'setUserToChat',];}public function setUserToChat(SetUserChatEvent $event): void{$user = $event->user;$dto = $event->dto;$channelId = $event->chatChannelId;$userId = $this->rocketChatClientService->createUser($dto);$chatSetting = new ChatSetting(Uuid::v4());$chatSetting->setChatUserId($userId);if ($user instanceof Student) {$user->setChatSetting($chatSetting);$this->addUserToChannel($channelId, $user);$this->generateToken($user);}if ($user instanceof User) {$user->setChatSetting($chatSetting);$this->addUserToChannel($channelId, $user);$this->generateToken($user);}$this->em->flush();}private function addUserToChannel(string $channelId, ChatUserInterface $user): void{$chatChannel = $this->chatChannelRepository->findOneBy(['chatChannelId' => $channelId]);if ($user instanceof Student) {$this->rocketChatClientService->inviteUserToChannel($user->getChatSetting()->getChatUserId(), $channelId);}if ($user instanceof User) {$this->rocketChatClientService->inviteUserToChannel($user->getChatSetting()->getChatUserId(), $channelId);}$user->getChatSetting()->addChatChannel($chatChannel);$this->em->persist($user);}private function generateToken(ChatUserInterface $user): void{$token = '';if ($user instanceof Student) {$token = $this->rocketChatClientService->createToken($user->getChatSetting()->getChatUserId());}if ($user instanceof User) {$token = $this->rocketChatClientService->createToken($user->getChatSetting()->getChatUserId());}$user->getChatSetting()->setToken($token);}}