src/InvoiceBundle/Listener/InvoicePaidListener.php line 46

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\PaymentBundle\Entity\Payment;
  18. use SolidInvoice\PaymentBundle\Repository\PaymentRepository;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. use Symfony\Component\Workflow\Event\Event;
  21. class InvoicePaidListener implements EventSubscriberInterface
  22. {
  23.     /**
  24.      * @return array<string, string>
  25.      */
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             'workflow.invoice.entered.paid' => 'onInvoicePaid',
  30.         ];
  31.     }
  32.     public function __construct(
  33.         private readonly ManagerRegistry $registry,
  34.     ) {
  35.     }
  36.     /**
  37.      * @throws MathException
  38.      */
  39.     public function onInvoicePaid(Event $event): void
  40.     {
  41.         /** @var Invoice $invoice */
  42.         $invoice $event->getSubject();
  43.         $em $this->registry->getManager();
  44.         /** @var PaymentRepository $paymentRepository */
  45.         $paymentRepository $em->getRepository(Payment::class);
  46.         $em->persist($invoice);
  47.         $totalPaid $paymentRepository->getTotalPaidForInvoice($invoice);
  48.         if ($totalPaid->isGreaterThan($invoice->getTotal())) {
  49.             $client $invoice->getClient();
  50.             /** @var CreditRepository $creditRepository */
  51.             $creditRepository $em->getRepository(Credit::class);
  52.             $creditRepository->addCredit($client$totalPaid->minus($invoice->getTotal()));
  53.         }
  54.         $em->flush();
  55.     }
  56. }