src/InvoiceBundle/Listener/Mailer/InvoicePdfListener.php line 40

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\Mailer;
  12. use Mpdf\MpdfException;
  13. use SolidInvoice\CoreBundle\Pdf\Generator;
  14. use SolidInvoice\InvoiceBundle\Email\InvoiceEmail;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Symfony\Component\Mailer\Event\MessageEvent;
  17. use Twig\Environment;
  18. use Twig\Error\LoaderError;
  19. use Twig\Error\RuntimeError;
  20. use Twig\Error\SyntaxError;
  21. /**
  22.  * @see \SolidInvoice\InvoiceBundle\Tests\Listener\Mailer\InvoicePdfListenerTest
  23.  */
  24. class InvoicePdfListener implements EventSubscriberInterface
  25. {
  26.     public function __construct(
  27.         private readonly Generator $generator,
  28.         private readonly Environment $twig
  29.     ) {
  30.     }
  31.     /**
  32.      * @throws MpdfException|LoaderError|RuntimeError|SyntaxError
  33.      */
  34.     public function __invoke(MessageEvent $event): void
  35.     {
  36.         /** @var InvoiceEmail $message */
  37.         $message $event->getMessage();
  38.         if ($message instanceof InvoiceEmail && $this->generator->canPrintPdf()) {
  39.             $content $this->generator->generate(
  40.                 $this->twig->render('@SolidInvoiceInvoice/Pdf/invoice.html.twig', ['invoice' => $message->getInvoice()])
  41.             );
  42.             $message->attach($content"invoice_{$message->getInvoice()->getId()}.pdf"'application/pdf');
  43.         }
  44.     }
  45.     public static function getSubscribedEvents(): array
  46.     {
  47.         return [
  48.             MessageEvent::class => '__invoke',
  49.         ];
  50.     }
  51. }