src/EventSubscriber/CompetitorDomainAdminSubscriber.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\CompetitorDomain;
  4. use App\Entity\Report;
  5. use App\Message\Report as ReportMessage;
  6. use App\Service\FaviconDownloader;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Messenger\MessageBusInterface;
  11. class CompetitorDomainAdminSubscriber implements EventSubscriberInterface
  12. {
  13.     private EntityManagerInterface $entityManager;
  14.     private MessageBusInterface $bus;
  15.     private FaviconDownloader $faviconDownloader;
  16.     public function __construct(EntityManagerInterface $entityManagerMessageBusInterface $busFaviconDownloader $faviconDownloader)
  17.     {
  18.         $this->entityManager $entityManager;
  19.         $this->bus $bus;
  20.         $this->faviconDownloader $faviconDownloader;
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             BeforeEntityPersistedEvent::class => [
  26.                 ['createReport'10],
  27.                 ['downloadFavicon', -10],
  28.             ],
  29.         ];
  30.     }
  31.     public function createReport(BeforeEntityPersistedEvent $event)
  32.     {
  33.         $entity $event->getEntityInstance();
  34.         if (!($entity instanceof CompetitorDomain)) {
  35.             return;
  36.         }
  37.         $report $this->entityManager->getRepository(Report::class)->findOneBy(
  38.             [
  39.                 'domain' => $entity->getDomain(),
  40.             ]
  41.         );
  42.         if (null !== $report) {
  43.             return;
  44.         }
  45.         $report = new Report();
  46.         $report->setDomain($entity->getDomain());
  47.         $this->entityManager->persist($report);
  48.         $this->entityManager->flush();
  49.         $this->bus->dispatch(
  50.             new ReportMessage($report->getId())
  51.         );
  52.     }
  53.     public function downloadFavicon(BeforeEntityPersistedEvent $event)
  54.     {
  55.         $entity $event->getEntityInstance();
  56.         if (!($entity instanceof CompetitorDomain)) {
  57.             return;
  58.         }
  59.         $domain $entity->getDomain();
  60.         if (empty($domain)) {
  61.             return;
  62.         }
  63.         $favicon $this->faviconDownloader->download($domain);
  64.         if ($favicon) {
  65.             $entity->setFavicon($favicon);
  66.             $this->entityManager->persist($entity);
  67.             $this->entityManager->flush();
  68.         }
  69.     }
  70. }