<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Employee;
use App\Entity\HolidayIncompatibility;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class DeleteEmployeeRemovedFromIncompatibleHolidaysSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function deleteEmployeeRemovedFromIncompatibleHolidays(ViewEvent $viewEvent) {
$employee = $viewEvent->getControllerResult();
$method = $viewEvent->getRequest()->getMethod();
if (!$employee instanceof Employee || Request::METHOD_PUT !== $method) {
return;
}
if (!$employee->isActive()) {
/** @var HolidayIncompatibility $holidayIncompatibilities */
$holidayIncompatibilities = $employee->getHolidayIncompatibilities();
/** @var HolidayIncompatibility $holidayIncompatibility */
foreach ($holidayIncompatibilities as $holidayIncompatibility) {
// $employees = $holidayIncompatibility->getEmployees();
$holidayIncompatibility->removeEmployee($employee);
$holidayIncompatibility->setMinNumberEmployees($holidayIncompatibility->getMinNumberEmployees()-1);
if (count($holidayIncompatibility->getEmployees()) == 1) {
// $aEmployee = $holidayIncompatibility->getEmployees()[0];
// $holidayIncompatibility->removeEmployee($aEmployee);
$this->entityManager->remove($holidayIncompatibility);
$this->entityManager->flush();
} else {
$this->entityManager->persist($holidayIncompatibility);
$this->entityManager->flush();
}
//
}
}
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['deleteEmployeeRemovedFromIncompatibleHolidays', EventPriorities::POST_WRITE],
];
}
}