<?php
namespace Harmonizely\Integration\BookingPayment\Subscribers;
use Doctrine\ORM\EntityManagerInterface;
use Harmonizely\CalendarEvents;
use Harmonizely\Integration\BookingPayment\Events\CancelBookingPaymentEvent;
use Harmonizely\Model\Cancellation;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Harmonizely\Model\EventPayment;
class CancelBookingPaymentEventSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
/**
* @var EventDispatcherInterface
*/
private EventDispatcherInterface $eventDispatcher;
/**
* SimplypayConfirmBookingPaymentEventSubscriber constructor.
*
* @param EntityManagerInterface $entityManager
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(
EntityManagerInterface $entityManager,
EventDispatcherInterface $eventDispatcher
)
{
$this->entityManager = $entityManager;
$this->eventDispatcher = $eventDispatcher;
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
CancelBookingPaymentEvent::NAME => 'onCancelPayment',
];
}
/**
* @param CancelBookingPaymentEvent $event
*/
public function onCancelPayment(CancelBookingPaymentEvent $event): void
{
$booking = $event->getBooking();
$payment = $booking->getPayment();
if ($payment) {
$oldPaymentStatus = $payment->getStatus();
if ($oldPaymentStatus === EventPayment::STATUS_RECEIVED) {
$this->eventDispatcher->dispatch(new GenericEvent($booking), CalendarEvents::EVENT_PRE_CANCEL);
$booking->removeSingleUseLink();
}
$cancellation = new Cancellation();
$cancellation->setReason('Cancelled from SimplyPay');
$cancellation->setCanceler($booking->getUser()->getFullName());
$booking->setCancellation($cancellation);
$booking->cancel();
$payment->cancel();
$this->entityManager->persist($booking);
$this->entityManager->flush();
if ($oldPaymentStatus === EventPayment::STATUS_RECEIVED) {
$this->eventDispatcher->dispatch(new GenericEvent($booking), CalendarEvents::EVENT_POST_CANCEL);
}
}
}
}