<?php
namespace App\EventListener;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Api\Dto\SendSignCode;
use App\Factory\SignatureFactory;
use App\Service\SignOperation;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class SendSignCodeSubscriber.
*/
final class SendSignCodeSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $manager;
/**
* @var SignatureFactory
*/
private $factory;
/**
* @var SignOperation
*/
private $signOperation;
/**
* SendSignCodeSubscriber constructor.
*
* @param EntityManagerInterface $manager
* @param SignatureFactory $factory
* @param SignOperation $signOperation
*/
public function __construct(EntityManagerInterface $manager, SignatureFactory $factory, SignOperation $signOperation)
{
$this->manager = $manager;
$this->factory = $factory;
$this->signOperation = $signOperation;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendSignatureCode', EventPriorities::POST_VALIDATE],
];
}
/**
* @param GetResponseForControllerResultEvent $event
*
* @throws \Doctrine\ORM\ORMException
*/
public function sendSignatureCode(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
if ('api_send_sign_codes_post_collection' !== $request->attributes->get('_route')) {
return;
}
/**
* @var SendSignCode $sendSignCode
*/
$sendSignCode = $event->getControllerResult();
$signature = $this->factory->createNew($sendSignCode->operation);
$signature->setCode(rand(10000, 99999));
$this->manager->persist($signature);
$this->manager->flush();
$this->signOperation->sendCode($signature);
$event->setResponse(new JsonResponse(null, 204));
}
}