<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Employee;
use App\Entity\User;
use App\Repository\UserRepository;
use App\Service\UserManipulatorService;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class CreateUserSubscriber implements EventSubscriberInterface
{
/**
* @var UserRepository
*/
private $userRepository;
/**
* @var UserPasswordEncoderInterface
*/
private $userPasswordEncoder;
/**
* @var UserManipulatorService
*/
private $generateUserFromEmployeeService;
public function __construct(UserRepository $userRepository, UserPasswordEncoderInterface $userPasswordEncoder,
UserManipulatorService $generateUserFromEmployeeService)
{
$this->userRepository = $userRepository;
$this->userPasswordEncoder = $userPasswordEncoder;
$this->generateUserFromEmployeeService = $generateUserFromEmployeeService;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['createUserFromEmployee', EventPriorities::POST_WRITE]
];
}
public function createUserFromEmployee(ViewEvent $viewEvent) {
/** @var Employee $employee */
$employee = $viewEvent->getControllerResult();
$method = $viewEvent->getRequest()->getMethod();
if (!$employee instanceof Employee || Request::METHOD_POST !== $method) {
return;
}
$this->generateUserFromEmployeeService->generateUserFromEmployee($employee);
}
}