-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMailer.php
More file actions
91 lines (73 loc) · 2.21 KB
/
Copy pathMailer.php
File metadata and controls
91 lines (73 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
declare(strict_types=1);
namespace Zero\Lib\Mail;
use Closure;
use InvalidArgumentException;
use Zero\Lib\Mail\Transport\SmtpTransport;
final class Mailer
{
private static ?self $instance = null;
/**
* @var array<string, mixed>
*/
private array $config;
private function __construct()
{
$this->config = config('mail');
}
public static function instance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public static function reset(): void
{
self::$instance = null;
}
/**
* Send a message using the configured mail transport.
*/
public static function send(Closure $callback): void
{
self::instance()->dispatch($callback);
}
/**
* Send a raw message without a callback.
*/
public static function raw(string $to, string $subject, string $body, bool $isHtml = false): void
{
self::instance()->dispatch(function (Message $message) use ($to, $subject, $body, $isHtml) {
$message->to($to)->subject($subject);
if ($isHtml) {
$message->html($body);
} else {
$message->text($body);
}
});
}
/**
* @param Closure(Message):void $callback
*/
public function dispatch(Closure $callback): void
{
$message = new Message($this->config['from'] ?? []);
$callback($message);
if ($message->getFrom() === null) {
throw new MailException('Email message must define a "From" address.');
}
if (empty($message->getEnvelopeRecipients())) {
throw new MailException('Email message must define at least one recipient.');
}
$transport = $this->resolveTransport($this->config['default'] ?? 'smtp');
$transport->send($message);
}
private function resolveTransport(string $driver): SmtpTransport
{
return match ($driver) {
'smtp' => new SmtpTransport($this->config['smtp'] ?? []),
default => throw new InvalidArgumentException(sprintf('Unsupported mail driver "%s".', $driver)),
};
}
}