<?php
 namespace App\ClientCollection\Customer; class EmailSend { private $emailData; public function __construct(\App\ClientCollection\Customer\EmailData $emailData) { $this->emailData = $emailData; } public function send() { if (!\DB::isInsideTransaction()) { throw new \Exception('The `send` method must be called inside transaction.'); } if ($this->emailData->getMessages()->hasErrorOrWarning()) { throw new \RuntimeException('Could not send email due to this error: '.$this->emailData->getMessages()->getMessageBulk()); } $emailActualData = $this->emailData->getData(); if (!$emailActualData['toFull']) { throw new \RuntimeException('There is no TO email configured for this invoice.'); } try { $mail = \Entity\Email::insert(); $emailConfig = \App\Config\AutoEmailSender::getInstance()->getAll(); $mail->fromEmail = $emailConfig['collectionReminders']['email']; $mail->fromName = $emailConfig['collectionReminders']['name']; $recipients = []; foreach ($emailActualData['toFull'] as $em) { $recipients[] = $em; } $mail->to = $recipients; $bccRecipients = []; foreach ($emailActualData['bccManual'] as $em) { $bccRecipients[] = $em; } if (!empty($bccRecipients)) { $mail->bcc = $bccRecipients; } $emailReplacingVars = $this->emailData->getVars(); $mail->subject = $this->replaceVars($emailActualData['subject'], $emailReplacingVars); $emailBody = htmlUnclean($emailActualData['body']); $mail->body = $this->replaceVars($emailBody, $emailReplacingVars); $mail->priority = 3; $mail->category = 'ClientCollection'; $mail->save(); } catch (\App\Entity\Exception $e) { throw new \RuntimeException("Could not create email due to a technical problem. Message: ".$e->getMessage()); } } private function replaceVars(string $content, array $emailVars) :string { $varsNames = array_map(function ($val) { return '%'.$val.'%'; }, array_keys($emailVars)); $varsValues = array_values($emailVars); $content = str_replace($varsNames, $varsValues, $content); return $content; } }