94 lines
2.6 KiB
PHP
94 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Mail\Transport;
|
|
|
|
use App\Services\ResendEmailService;
|
|
use Symfony\Component\Mailer\Exception\TransportException;
|
|
use Symfony\Component\Mailer\SentMessage;
|
|
use Symfony\Component\Mailer\Transport\AbstractTransport;
|
|
use Symfony\Component\Mime\Email;
|
|
|
|
class ResendCurlTransport extends AbstractTransport
|
|
{
|
|
public function __construct(
|
|
private readonly ResendEmailService $service,
|
|
private readonly string $defaultFromAddress,
|
|
private readonly ?string $defaultFromName = null,
|
|
) {
|
|
parent::__construct();
|
|
}
|
|
|
|
public function __toString(): string
|
|
{
|
|
return 'resend_curl';
|
|
}
|
|
|
|
protected function doSend(SentMessage $message): void
|
|
{
|
|
$originalMessage = $message->getOriginalMessage();
|
|
|
|
if (! $originalMessage instanceof Email) {
|
|
throw new TransportException('Resend transport hanya mendukung Symfony Email.');
|
|
}
|
|
|
|
$fromAddresses = $originalMessage->getFrom();
|
|
$from = $fromAddresses !== []
|
|
? $this->stringifyAddresses([$fromAddresses[0]])[0]
|
|
: $this->formatFrom($this->defaultFromAddress, $this->defaultFromName);
|
|
|
|
$to = $this->stringifyAddresses($originalMessage->getTo());
|
|
|
|
if ($to === []) {
|
|
throw new TransportException('Penerima email kosong.');
|
|
}
|
|
|
|
$payload = [
|
|
'from' => $from,
|
|
'to' => count($to) === 1 ? $to[0] : $to,
|
|
'subject' => $originalMessage->getSubject() ?? '',
|
|
];
|
|
|
|
$htmlBody = $this->normalizeBody($originalMessage->getHtmlBody());
|
|
$textBody = $this->normalizeBody($originalMessage->getTextBody());
|
|
|
|
if ($htmlBody !== null) {
|
|
$payload['html'] = $htmlBody;
|
|
}
|
|
|
|
if ($textBody !== null) {
|
|
$payload['text'] = $textBody;
|
|
}
|
|
|
|
$response = $this->service->send($payload);
|
|
|
|
if (isset($response['id']) && is_string($response['id'])) {
|
|
$message->setMessageId($response['id']);
|
|
}
|
|
|
|
$message->appendDebug(json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '');
|
|
}
|
|
|
|
private function formatFrom(string $address, ?string $name): string
|
|
{
|
|
return $name ? sprintf('%s <%s>', $name, $address) : $address;
|
|
}
|
|
|
|
private function normalizeBody(mixed $body): ?string
|
|
{
|
|
if ($body === null) {
|
|
return null;
|
|
}
|
|
|
|
if (is_resource($body)) {
|
|
$body = stream_get_contents($body);
|
|
}
|
|
|
|
if (! is_string($body)) {
|
|
return null;
|
|
}
|
|
|
|
$body = trim($body);
|
|
|
|
return $body === '' ? null : $body;
|
|
}
|
|
} |