From b6c9fd879f6fa32d300d5e26cad765b2db91c230 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4fer?= Date: Fri, 6 Aug 2021 12:07:22 +0200 Subject: [PATCH] Fix sending emails when storing invoices in S3 --- src/Email/InvoiceEmailSender.php | 19 +++++++++--- src/Filesystem/TemporaryFilesystem.php | 40 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 src/Filesystem/TemporaryFilesystem.php diff --git a/src/Email/InvoiceEmailSender.php b/src/Email/InvoiceEmailSender.php index cd2d357b..e60b8e29 100644 --- a/src/Email/InvoiceEmailSender.php +++ b/src/Email/InvoiceEmailSender.php @@ -16,6 +16,7 @@ use Sylius\Component\Mailer\Sender\SenderInterface; use Sylius\InvoicingPlugin\Entity\InvoiceInterface; use Sylius\InvoicingPlugin\Provider\InvoiceFileProviderInterface; +use Sylius\InvoicingPlugin\Filesystem\TemporaryFilesystem; final class InvoiceEmailSender implements InvoiceEmailSenderInterface { @@ -25,12 +26,16 @@ final class InvoiceEmailSender implements InvoiceEmailSenderInterface /** @var InvoiceFileProviderInterface */ private $invoiceFileProvider; + /** @var TemporaryFilesystem */ + private $temporaryFilesystem; + public function __construct( SenderInterface $emailSender, InvoiceFileProviderInterface $invoiceFileProvider ) { $this->emailSender = $emailSender; $this->invoiceFileProvider = $invoiceFileProvider; + $this->temporaryFilesystem = new TemporaryFilesystem(); } public function sendInvoiceEmail( @@ -39,9 +44,15 @@ public function sendInvoiceEmail( ): void { $invoicePdf = $this->invoiceFileProvider->provide($invoice); - $this - ->emailSender - ->send(Emails::INVOICE_GENERATED, [$customerEmail], ['invoice' => $invoice], [$invoicePdf->fullPath()]) - ; + // Since Sylius' Mailer does not support sending attachments which aren't real files + // we have to simulate the file being on the local filesystem, so that we save the PDF, + // run the callable and delete it when the callable is finished. + $this->temporaryFilesystem->executeWithFile( + $invoicePdf->filename(), + $invoicePdf->content(), + function (string $filepath) use ($invoice, $customerEmail): void { + $this->emailSender->send(Emails::INVOICE_GENERATED, [$customerEmail], ['invoice' => $invoice], [$filepath]); + } + ); } } diff --git a/src/Filesystem/TemporaryFilesystem.php b/src/Filesystem/TemporaryFilesystem.php new file mode 100644 index 00000000..9b31bfa4 --- /dev/null +++ b/src/Filesystem/TemporaryFilesystem.php @@ -0,0 +1,40 @@ +targetDirectory = rtrim($targetDirectory ?? sys_get_temp_dir(), \DIRECTORY_SEPARATOR); + } + + public function executeWithFile(string $filename, string $content, callable $callback): void + { + $filepath = $this->targetDirectory . \DIRECTORY_SEPARATOR . $filename; + + if (!file_put_contents($filepath, $content)) { + throw new \RuntimeException(sprintf('Could not create file "%s"!', $filepath)); + } + + try { + $callback($filepath); + } finally { + unlink($filepath); + } + } +}