<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 18/03/2019
* Time: 09:09 AM
*/
namespace App\EventSubscriber\User;
use App\Services\UtilsService;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Repository\App\VendorRepository;
use App\Repository\App\RoleRepository;
use App\Exception\AccessDeniedException;
use App\Exception\NotFoundException;
use App\Services\VendorService;
use App\Entity\App\User;
class UserPreWriteSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $authorizationChecker;
private $vendorRepository;
private $roleRepository;
private $vendorService;
private $entityManager;
private $utilsService;
public function __construct(
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $checker,
VendorRepository $vendorRepository,
RoleRepository $roleRepository,
VendorService $vendorService,
EntityManagerInterface $entityManager,
UtilsService $utilsService)
{
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $checker;
$this->vendorService = $vendorService;
$this->vendorRepository = $vendorRepository;
$this->roleRepository = $roleRepository;
$this->entityManager = $entityManager;
$this->utilsService = $utilsService;
}
/**
* @param ViewEvent $event
* @throws AccessDeniedException
* @throws NotFoundException
*/
public function onKernelView(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
$userCurrent = $this->tokenStorage->getToken()->getUser();
if (!($user instanceof User) || Request::METHOD_DELETE !== $method)
return;
if (!$userCurrent instanceof User)
throw new NotFoundException('User not found');
if (!$userCurrent === $user) {
throw new AccessDeniedException('You can not delete yourself');
}
if ($this->authorizationChecker->isGranted('ROLE_SUPERADMIN'))
{
$this->onDeleteCascade($user);
return;
}
throw new AccessDeniedException('Action Denied');
}
/**
* @param User $user
*/
protected function onDeleteCascade(User $user)
{
foreach ($user->getVendorStaff() as $vendorStaff) {
$this->entityManager->remove($vendorStaff);
}
$this->entityManager->flush();
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::PRE_WRITE]
];
}
}