|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Notifier\Channel\Email; |
|
6
|
|
|
|
|
7
|
|
|
use ErrorException; |
|
8
|
|
|
use Notifier\Channel\Exception\SendingMessageFailed; |
|
9
|
|
|
|
|
10
|
|
|
final class SimpleMailer implements Mailer |
|
11
|
|
|
{ |
|
12
|
|
|
private const MESSAGE_LINE_CHARACTERS_LIMIT = 70; |
|
13
|
|
|
|
|
14
|
|
|
/** @var callable|null */ |
|
15
|
|
|
private $handler; |
|
16
|
|
|
|
|
17
|
|
|
/** @var EmailMessage */ |
|
18
|
|
|
private $message; |
|
19
|
|
|
|
|
20
|
1 |
|
public function __construct(callable $handler = null) |
|
21
|
|
|
{ |
|
22
|
1 |
|
$this->handler = $handler; |
|
23
|
1 |
|
} |
|
24
|
|
|
|
|
25
|
1 |
|
public function send(EmailMessage $message): void |
|
26
|
|
|
{ |
|
27
|
1 |
|
$this->message = $message; |
|
28
|
|
|
|
|
29
|
1 |
|
$status = call_user_func( |
|
30
|
1 |
|
$this->handler ?? 'mail', |
|
31
|
1 |
|
$this->buildTo(), |
|
32
|
1 |
|
$this->buildSubject(), |
|
33
|
1 |
|
$this->buildMessage(), |
|
34
|
1 |
|
$this->buildHeaders() |
|
35
|
|
|
); |
|
36
|
|
|
|
|
37
|
1 |
|
if (!$status) { |
|
38
|
|
|
$error = error_get_last(); |
|
39
|
|
|
throw SendingMessageFailed::dueTo(new ErrorException($error['message'] ?? 'Email has not been accepted for delivery')); |
|
40
|
|
|
} |
|
41
|
1 |
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
private function buildTo(): string |
|
44
|
|
|
{ |
|
45
|
1 |
|
return implode(', ', $this->message->getTo()); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
private function buildSubject(): string |
|
49
|
|
|
{ |
|
50
|
1 |
|
return $this->message->getSubject(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
1 |
|
private function buildMessage(): string |
|
54
|
|
|
{ |
|
55
|
1 |
|
return wordwrap($this->message->getBody(), self::MESSAGE_LINE_CHARACTERS_LIMIT); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
1 |
|
private function buildHeaders(): string |
|
59
|
|
|
{ |
|
60
|
|
|
$headers = array_map(function (string $name, $value) { |
|
61
|
1 |
|
if (is_array($value)) { |
|
62
|
1 |
|
$value = implode(', ', $value); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
return "$name: $value"; |
|
66
|
1 |
|
}, array_keys($this->message->getHeaders()), $this->message->getHeaders()); |
|
67
|
|
|
|
|
68
|
1 |
|
return implode("\r\n", $headers); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|