<?php
namespace App\EventSubscriber;
use App\Entity\CompetitorDomain;
use App\Entity\Report;
use App\Message\Report as ReportMessage;
use App\Service\FaviconDownloader;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\MessageBusInterface;
class CompetitorDomainAdminSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
private MessageBusInterface $bus;
private FaviconDownloader $faviconDownloader;
public function __construct(EntityManagerInterface $entityManager, MessageBusInterface $bus, FaviconDownloader $faviconDownloader)
{
$this->entityManager = $entityManager;
$this->bus = $bus;
$this->faviconDownloader = $faviconDownloader;
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => [
['createReport', 10],
['downloadFavicon', -10],
],
];
}
public function createReport(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof CompetitorDomain)) {
return;
}
$report = $this->entityManager->getRepository(Report::class)->findOneBy(
[
'domain' => $entity->getDomain(),
]
);
if (null !== $report) {
return;
}
$report = new Report();
$report->setDomain($entity->getDomain());
$this->entityManager->persist($report);
$this->entityManager->flush();
$this->bus->dispatch(
new ReportMessage($report->getId())
);
}
public function downloadFavicon(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof CompetitorDomain)) {
return;
}
$domain = $entity->getDomain();
if (empty($domain)) {
return;
}
$favicon = $this->faviconDownloader->download($domain);
if ($favicon) {
$entity->setFavicon($favicon);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}
}