<?php
namespace App\Subscriber\Payment;
use App\Dictionary\PaymentType;
use App\Event\Payment\BookingCreatedEvent;
use App\Event\Payment\PaymentCreatedEvent;
use App\Service\Payment\PaymentProcessService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PaymentProcessSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
protected PaymentProcessService $service;
/**
* PaymentProcessSubscriber constructor.
*/
public function __construct(PaymentProcessService $service, EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
$this->service = $service;
}
public static function getSubscribedEvents(): array
{
return [
PaymentCreatedEvent::class => [
['lockPaymentProcess', 0],
],
BookingCreatedEvent::class => [
['onBookingCreatedCreatePaymentProcess', 0],
],
];
}
/**
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onBookingCreatedCreatePaymentProcess(BookingCreatedEvent $event): bool
{
$account = $event->getAccount();
$member = $account->getMember();
$booking = $event->getBooking();
$process = $this->service->createPaymentProcessForMember($member, $booking->getUuidForPaymentProcess());
$this->service->pickPaymentMethod($process, $booking->getMethod());
if ($tariff = $booking->getMethod()->getTariffByAmount($booking->getAmount())) {
$this->service->pickPaymentTariff($process, $tariff);
}
$booking->setPaymentProcess($process);
return true;
}
public function lockPaymentProcess(PaymentCreatedEvent $event)
{
$payment = $event->getPayment();
if (PaymentType::BOOKING !== $payment->getType()) {
return;
}
$process = $payment->getPaymentProcess();
if ($process) {
$process->setIsLocked(true);
$this->entityManager->persist($process);
$this->entityManager->flush();
}
}
}