<?php
namespace App\EventSubscriber;
use App\Entity\Aviso;
use App\Enum\TipoAvisoEnum;
use App\Interfaces\AvisoRepositoryInterface;
use App\Interfaces\PropietarioContenidoRepositoryInterface;
use App\Services\AsymmetricEncryptionService;
use App\Services\EventDomain\ForoChangedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Translation\Translator;
class ForoEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private AsymmetricEncryptionService $asymmetricEncryptionService,
private PropietarioContenidoRepositoryInterface $propietarioContenidoRepository,
private AvisoRepositoryInterface $avisoRepository,
private Translator $translator,
private UrlGeneratorInterface $urlGenerator,
)
{
}
public static function getSubscribedEvents()
{
return [
ForoChangedEvent::class => 'onChangedForo',
];
}
public function onChangedForo(ForoChangedEvent $event): void
{
$mensaje = $event->getMensajeForo();
$tema = $event->getMensajeForo()->getTema();
$propietariosForo = $this->propietarioContenidoRepository->getPropietariosByTema($tema);
$propietariosAvisos = $this->avisoRepository->getPropietariosByObjectDeleted($tema);
$propietarios = array_diff($propietariosForo, $propietariosAvisos, [$mensaje->getPropietarioContenido()]);
//Obtener avisos
foreach ($propietarios as $propietario) {
$avisosPropietario = $this->avisoRepository->getAvisosForoByPropietarioTema($propietario, $tema);
$i = 0;
$aviso = new Aviso();
foreach ($avisosPropietario as $avisoPropietario)
{
if($i !== 0)
{
$this->avisoRepository->delete($avisoPropietario, true);
}
else
{
$aviso = $avisoPropietario;
}
$i++;
}
$aviso->setTipo(TipoAvisoEnum::AVISO_FORO);
$aviso->setFecha($mensaje->getCreatedAt());
$aviso->setAsunto($this->translator->trans('new.ads.foro', ['%tema%' => $tema], 'ads'));
$aviso->setPropietarioContenido($propietario);
$aviso->setObject($mensaje);
$aviso->setTema($tema);
$aviso->setDeletedAt(null);
$token = $this->asymmetricEncryptionService->hybridEncrypt([
'tipoAviso' => TipoAvisoEnum::AVISO_FORO,
'propietarioId' => $aviso->getPropietarioContenido()?->getId(),
'url' => $this->urlGenerator->generate('mensaje_foro_list', ['id' => $tema->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
]);
$aviso->setTokenHash($token);
$this->avisoRepository->save($aviso);
}
}
}