<?php declare(strict_types=1);
namespace App\Subscriber;
use App\Entity\User;
use App\Event\Recurring\MembershipPaymentCancelledEvent;
use App\Event\Recurring\MembershipPaymentReceivedEvent;
use App\Payment\Recurring\CreditsMembershipProcessor;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class MembershipPaymentSubscriber implements EventSubscriberInterface
{
private CreditsMembershipProcessor $creditsMembershipProcessor;
private LoggerInterface $paymentLogger;
public function __construct(CreditsMembershipProcessor $creditsMembershipProcessor, LoggerInterface $paymentLogger)
{
$this->creditsMembershipProcessor = $creditsMembershipProcessor;
$this->paymentLogger = $paymentLogger;
}
public function onPaymentReceived(MembershipPaymentReceivedEvent $event): void
{
$this->paymentLogger->info(
sprintf(
'Received a new payment event for user: %s transactionId: %s',
$event->getUser()->getId(),
$event->getTransactionId()
)
);
}
public function onPaymentCancelled(MembershipPaymentCancelledEvent $event): void
{
$user = $event->getUser();
if (!$user instanceof User) {
throw new UnexpectedTypeException($user, User::class);
}
$this->paymentLogger->info(
sprintf(
'Received a cancel payment event for user: %s transactionId: %s',
$event->getUser()->getId(),
$event->getTransactionId()
)
);
$this->creditsMembershipProcessor->cancelNow($user, $event->getCreditsMembership());
$event->getCreditsMembership()->setTransactionRefunded($event->getTransactionId());
}
/**
* @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
*/
public static function getSubscribedEvents(): array
{
return [
MembershipPaymentReceivedEvent::class => 'onPaymentReceived',
MembershipPaymentCancelledEvent::class => 'onPaymentCancelled',
];
}
}