<?php
namespace App\EventSubscriber;
use App\Entity\BankSimulation;
use App\Mybase\Services\Base\SBase;
use App\Repository\BankSimulationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class BankSimulationSubscriber implements EventSubscriberInterface
{
/**
* @var SBase
*/
private $base;
/**
* @var BankSimulationRepository
*/
private $repo;
/**
* @var EntityManagerInterface
*/
private $em;
public function __construct(
SBase $base,
BankSimulationRepository $repo,
EntityManagerInterface $em
) {
$this->base = $base;
$this->repo = $repo;
$this->em = $em;
}
/**
* @return void
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$object = $request->get('_api_resource_class');
$datas = $this->base->getPostedData($request);
if (
$object === BankSimulation::class
&& $request->getMethod() === 'POST'
) {
$banks = $this->repo->findBy(['theProperty' => $datas['theProperty']]);
if ($banks !== []) {
foreach ($banks as $bank) {
$this->em->remove($bank);
}
$this->em->flush();
}
$bank = $this->base->deserialize($datas, BankSimulation::class, 'json');
$this->em->persist($bank);
$this->em->flush();
$event->setResponse($this->base->jsonResponseOk($datas, 'My Bank'));
return;
}
if (
$object === BankSimulation::class
&& $request->getMethod() === 'GET'
) {
$theProperty = (int) $request->query->get('theProperty') !== 0 ? (int) $request->query->get('theProperty') : null;
if ($theProperty !== null) {
$bankSimulation = $this->base->getRepository(BankSimulation::class)->findBy(['theProperty' => $theProperty]);
if ($bankSimulation !== []) {
$data = $this->base->serialize($bankSimulation[0], 'json', ['groups' => 'bank:read']);
$event->setResponse($this->base->jsonResponseOk($data, 'My Bank'));
return;
}
}
$event->setResponse($this->base->jsonResponseBadRequest('No simulation bank for this property'));
return;
}
}
/**
* @return void
*/
public static function getSubscribedEvents()
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}