<?php
namespace App\EventSubscriber;
use App\Entity\ApplicantReview;
use App\Entity\Applicants;
use App\Entity\Jobs;
use App\Features\Applicant\ApplicantFilter;
use App\Features\Mailer\Exception\IMailerException;
use App\Features\Mailer\IMailer;
use App\Repository\ApplicantsRepository;
use OSAdmin\Event\OSAdminPersistEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class OSAdminEventSubscriberSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly ApplicantsRepository $repository,
private IMailer $applicantMailer,
private Security $security,
private UrlGeneratorInterface $generator){}
public static function getSubscribedEvents(): array
{
return [
OSAdminPersistEvent::NAME => 'onPersist',
];
}
public function onPersist(OSAdminPersistEvent $event): void
{
$object = $event->getEntity();
if($object instanceof Jobs){
$job = $object;
$activitySectors= $job->getSectors();
// send mail to all applicant whose sector is in the $activitySectors
$filter= (new ApplicantFilter())
->setSectors($activitySectors->toArray())
->setEnabled(true);
$applicants = $this->repository->filter($filter)->getQuery()->getResult();
// filter applicant who when receive new job notification is true
$applicants = array_filter($applicants, static fn(Applicants $applicant) => $applicant->getConfig() && $applicant->getConfig()->getReceiveNewJobAlert());
if($applicants){
$jobLink= $this->generator->generate('job-detail', ['uuid' => $job->getUuid()], UrlGeneratorInterface::ABSOLUTE_URL);
// send mail to all applicant with message: "Une nouvelle offre d'emploi a été publiée dans votre secteur d'activité. Le lien vers la page de l'offre d'emploi est $jobLink."
$text= "Une nouvelle offre d'emploi a été publiée dans votre secteur d'activité. Le lien vers la page de l'offre d'emploi est $jobLink.";
$html= "<p>Une nouvelle offre d'emploi a été publiée dans votre secteur d'activité. Le lien vers la page de l'offre d'emploi est <a href='$jobLink'>$jobLink</a></p>";
try {
$this->applicantMailer->send($html, $text, ...$applicants);
} catch (IMailerException $e) {
}
}
}
if($object instanceof ApplicantReview){
$object->setCreatedBy($this->security->getUser());
}
}
}