src/InvoiceBundle/Listener/InvoiceCancelListener.php line 49

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of SolidInvoice project.
  5.  *
  6.  * (c) Pierre du Plessis <open-source@solidworx.co>
  7.  *
  8.  * This source file is subject to the MIT license that is bundled
  9.  * with this source code in the file LICENSE.
  10.  */
  11. namespace SolidInvoice\InvoiceBundle\Listener;
  12. use Brick\Math\Exception\MathException;
  13. use Doctrine\Persistence\ManagerRegistry;
  14. use SolidInvoice\ClientBundle\Entity\Credit;
  15. use SolidInvoice\ClientBundle\Repository\CreditRepository;
  16. use SolidInvoice\InvoiceBundle\Entity\Invoice;
  17. use SolidInvoice\InvoiceBundle\Event\InvoiceEvent;
  18. use SolidInvoice\InvoiceBundle\Event\InvoiceEvents;
  19. use SolidInvoice\PaymentBundle\Entity\Payment;
  20. use SolidInvoice\PaymentBundle\Model\Status;
  21. use SolidInvoice\PaymentBundle\Repository\PaymentRepository;
  22. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  23. use function assert;
  24. class InvoiceCancelListener implements EventSubscriberInterface
  25. {
  26.     /**
  27.      * @return array<string, string>
  28.      */
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             InvoiceEvents::INVOICE_POST_CANCEL => 'onInvoiceCancelled',
  33.         ];
  34.     }
  35.     public function __construct(
  36.         private readonly ManagerRegistry $registry,
  37.     ) {
  38.     }
  39.     /**
  40.      * @throws MathException
  41.      */
  42.     public function onInvoiceCancelled(InvoiceEvent $event): void
  43.     {
  44.         $invoice $event->getInvoice();
  45.         assert($invoice instanceof Invoice);
  46.         /** @var PaymentRepository $paymentRepository */
  47.         $paymentRepository $this->registry->getRepository(Payment::class);
  48.         $em $this->registry->getManager();
  49.         $invoice->setBalance($invoice->getTotal());
  50.         $em->persist($invoice);
  51.         $totalPaid $paymentRepository->getTotalPaidForInvoice($invoice);
  52.         if ($totalPaid->isPositive()) {
  53.             $paymentRepository->updatePaymentStatus($invoice->getPayments(), Status::STATUS_CREDIT);
  54.             /** @var CreditRepository $creditRepository */
  55.             $creditRepository $this->registry->getRepository(Credit::class);
  56.             $creditRepository->addCredit($invoice->getClient(), $totalPaid);
  57.         }
  58.         $em->flush();
  59.     }
  60. }