<?php
namespace App\EventListener;
use App\Entity\JobAlertSetting;
use App\Entity\Option;
use App\Event\SettingPrePersistEvent;
use Doctrine\ORM\EntityManagerInterface;
class JobAlertSettingListener
{
/**
* @var EntityManagerInterface
*/
private $manager;
public function __construct(EntityManagerInterface $manager)
{
$this->manager = $manager;
}
public function onPrePersist(SettingPrePersistEvent $event)
{
$setting = $event->getSetting();
if (!$setting instanceof JobAlertSetting) {
return;
}
// remove existing option JobAlertSettings
$optionGroups = $this->manager->getRepository(Option::class)->findAll();
foreach ($optionGroups as $optionGroup) {
$optionGroup->setJobAlertSetting(null);
$this->manager->persist($optionGroup);
}
$this->manager->flush();
// add option JobAlertSettings
foreach ($setting->getOptionGroups() as &$optionGroup) {
$optionGroup->setJobAlertSetting($setting);
}
}
}