src/EventSubscriber/AddScheduleToEmployeeSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\Employee;
  5. use App\Entity\Schedule;
  6. use App\Repository\ScheduleRepository;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. class AddScheduleToEmployeeSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var EntityManagerInterface
  16.      */
  17.     private $manager;
  18.     public function __construct(EntityManagerInterface $manager)
  19.     {
  20.         $this->manager $manager;
  21.     }
  22.     public function assignSchedule(ViewEvent $viewEvent)
  23.     {
  24.         $employee $viewEvent->getControllerResult();
  25.         $method $viewEvent->getRequest()->getMethod();
  26.         if (!$employee instanceof Employee || Request::METHOD_POST !== $method) {
  27.             return;
  28.         }
  29.         $schedule $this->manager->getRepository(Schedule::class)->findOneBy(['name' => 'general']);
  30.         $employee->setSchedule($schedule);
  31.         $this->manager->persist($employee);
  32.         $this->manager->flush();
  33.     }
  34.     public static function getSubscribedEvents()
  35.     {
  36.         return [
  37.             KernelEvents::VIEW => ['assignSchedule'EventPriorities::POST_WRITE],
  38.         ];
  39.     }
  40. }