<?php declare(strict_types=1);
namespace App\Subscriber;
use App\Email\CardExpiration;
use App\Entity\User;
use App\Repository\PaymentVxsOrderRepository;
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Sindrive\EmailSenderBundle\Service\EmailSender;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use VxsBundle\Event\VxsPaymentApprovalsEvent;
class CardExpirationSubscriber implements EventSubscriberInterface
{
private PaymentVxsOrderRepository $paymentVxsOrderRepository;
private ManagerRegistry $doctrine;
private EmailSender $emailSender;
public function __construct(PaymentVxsOrderRepository $paymentVxsOrderRepository, ManagerRegistry $doctrine, EmailSender $emailSender)
{
$this->paymentVxsOrderRepository = $paymentVxsOrderRepository;
$this->doctrine = $doctrine;
$this->emailSender = $emailSender;
}
public function onApproved(VxsPaymentApprovalsEvent $event): void
{
$transactions = $event->getApprovedTransactions();
$nearExpired = new DateTime('+2 months');
$nearExpired->modify('first day of this month')->setTime(0, 0, 0, 0);
foreach ($transactions as $transactionId => $transactionData) {
if (!isset($transactionData['expiry']) || !is_string($transactionData['expiry'])) {
continue;
}
$date = DateTime::createFromFormat('Y-m-d', $transactionData['expiry']);
if (false === $date) {
continue;
}
$date->setTime(0, 0, 0, 0);
if ($date > $nearExpired) {
continue;
}
$transaction = $this->paymentVxsOrderRepository->findOneBy(['transactionId' => $transactionId]);
if (null === $transaction) {
continue;
}
if (null === $transaction->getCreditsMembership()) {
continue;
}
$user = $transaction->getUser();
if (!$user instanceof User) {
continue;
}
if ($user->getNotifiedExpiration($transactionId)) {
continue;
}
$user->setEmailNotifiedExpiration($transactionId);
$this->emailSender->sendType(new CardExpiration($user));
}
$this->doctrine->getManager()->flush();
}
/**
* @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
*/
public static function getSubscribedEvents(): array
{
return [
VxsPaymentApprovalsEvent::class => 'onApproved',
];
}
}