<?php
/*
* This file is part of the CosaVostra, TrackPay package.
*
* (c) Mohamed Radhi GUENNICHI <rg@mate.tn> <+216 50 711 816>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\GoCardlessAccount;
use App\Entity\GoCardlessMandate;
use App\Event\GoCardlessMandateEvent;
use App\Manager\PaymentManager;
use App\Manager\ProcedureManager;
use App\Repository\GoCardlessAccountRepository;
use App\Service\GoCardlessService;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class GoCardlessMandateSubscriber implements EventSubscriberInterface
{
/**
* @var PaymentManager
*/
protected $paymentManager;
/**
* @var GoCardlessService
*/
protected $gocardlessService;
/**
* @var GoCardlessAccountRepository
*/
protected $accountRepository;
/**
* @var ProcedureManager
*/
protected $procedureManager;
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct(PaymentManager $paymentManager, GoCardlessService $gocardlessService, GoCardlessAccountRepository $accountRepository, ProcedureManager $procedureManager, EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager)
{
$this->paymentManager = $paymentManager;
$this->gocardlessService = $gocardlessService;
$this->accountRepository = $accountRepository;
$this->procedureManager = $procedureManager;
$this->eventDispatcher = $eventDispatcher;
$this->entityManager = $entityManager;
}
public function onMandate(GoCardlessMandateEvent $event): void
{
$mandate = $event->getMandate();
$invoice = $mandate->getInvoice();
// Create a new payment record with pending status
$procedure = $invoice->getProcedure();
if ($mandate->getChargeDate() <= new DateTime()) {
$account = $this->accountRepository->findOneByUser($invoice->getUser());
// Pay now
$gcPayment = $this->gocardlessService->connect($account->getCredential(GoCardlessAccount::CREDENTIAL_ACCESS_TOKEN))
->payments()->create([
'params' => [
'amount' => $invoice->getDueAmount(),
'currency' => 'EUR',
'links' => [
'mandate' => $mandate->getMandateId()
],
'metadata' => [
'invoice_number' => $invoice->getName()
]
]
]);
$this->paymentManager->order($invoice = $mandate->getInvoice(), $gcPayment->id, $mandate);
$mandate->setStatus(GoCardlessMandate::STATUS_PROCESSING);
$this->entityManager->flush();
// Stop.
return;
}
// Pause the procedure related to the invoice.
$this->procedureManager->pause($procedure);
}
public static function getSubscribedEvents()
{
return [
GoCardlessMandateEvent::class => 'onMandate'
];
}
}