<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Employee;
use App\Entity\Schedule;
use App\Repository\ScheduleRepository;
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 AddScheduleToEmployeeSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $manager;
public function __construct(EntityManagerInterface $manager)
{
$this->manager = $manager;
}
public function assignSchedule(ViewEvent $viewEvent)
{
$employee = $viewEvent->getControllerResult();
$method = $viewEvent->getRequest()->getMethod();
if (!$employee instanceof Employee || Request::METHOD_POST !== $method) {
return;
}
$schedule = $this->manager->getRepository(Schedule::class)->findOneBy(['name' => 'general']);
$employee->setSchedule($schedule);
$this->manager->persist($employee);
$this->manager->flush();
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['assignSchedule', EventPriorities::POST_WRITE],
];
}
}