src/Core/Application/EventSubscriber/Chat/ChatChannelCreatedSubscriber.php line 36

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Core\Application\EventSubscriber\Chat;
  4. use App\Admin\Domain\Repository\Course\CourseRepositoryInterface;
  5. use App\Core\Application\Event\Chat\ChatChannelCreatedEvent;
  6. use App\Core\Application\Service\RocketChat\RocketChatClientServiceInterface;
  7. use App\Core\Domain\Entity\ChatSetting\ChatChannel;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Uid\Uuid;
  11. class ChatChannelCreatedSubscriber implements EventSubscriberInterface
  12. {
  13.     private readonly RocketChatClientServiceInterface $rocketChatClientService;
  14.     private readonly EntityManagerInterface $em;
  15.     public function __construct(
  16.         EntityManagerInterface $em,
  17.         RocketChatClientServiceInterface $rocketChatClientService,
  18.         private readonly CourseRepositoryInterface $courseRepository
  19.     ) {
  20.         $this->rocketChatClientService $rocketChatClientService;
  21.         $this->em $em;
  22.     }
  23.     public static function getSubscribedEvents(): array
  24.     {
  25.         return [
  26.             ChatChannelCreatedEvent::class => 'createChannel',
  27.         ];
  28.     }
  29.     public function createChannel(ChatChannelCreatedEvent $event): void
  30.     {
  31.         $courseId $event->courseId;
  32.         $course $this->courseRepository->find(['id' => $courseId]);
  33.         $channelId $this->rocketChatClientService->createChannel($this->parseName($course->getName()));
  34.         if (!$channelId) {
  35.             throw new \RuntimeException('Nie udało się utworzyć kanału czatu w RocketChat.');
  36.         }
  37.         $chatChannel = new ChatChannel(Uuid::v4());
  38.         $chatChannel->setCourse($course);
  39.         $chatChannel->setChatChannelId($channelId);
  40.         $this->em->persist($chatChannel);
  41.         $this->em->flush();
  42.     }
  43.     private function parseName(string $input): string
  44.     {
  45.         $lowercase mb_strtolower($input'UTF-8');
  46.         $transliterated iconv('UTF-8''ASCII//TRANSLIT'$lowercase);
  47.         $cleaned preg_replace('/[^a-z0-9]+/''_'$transliterated);
  48.         return trim($cleaned'_');
  49.     }
  50. }