<?php
/**
* Subscriber delete site
*
* @package RMCS
* @author Vlad Shashkov <vlad.s@zimalab.com>
* @copyright 2014 - 2019 The Zimalab
*/
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Main\{Site, Tru};
use Doctrine\Persistence\{ManagerRegistry, ObjectManager};
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\HttpKernel\{Event\ViewEvent, Exception\HttpException, KernelEvents};
class RemoveSiteSubscriber implements EventSubscriberInterface
{
/**
* @var ObjectManager
*/
private $em;
/**
* RemoveSiteSubscriber constructor.
*
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
$this->em = $registry->getManager('default');
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['onDelete', EventPriorities::PRE_VALIDATE],
];
}
/**
* Event check is tied tru
*
* @param ViewEvent $event
*/
public function onDelete(ViewEvent $event): void
{
$site = $event->getControllerResult();
$request = $event->getRequest();
if ($site instanceof Site && $event->getRequest()->getMethod() == Request::METHOD_DELETE) {
$id = $request->get('id');
$tru = $this->em
->getRepository(Tru::class)
->findOneBy(['site' => $id]);
if ($tru) {
throw new HttpException(Response::HTTP_UNPROCESSABLE_ENTITY, 'This site is tied to Tru');
}
}
}
}