1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Notifier\Channel\Email; |
6
|
|
|
|
7
|
|
|
use Notifier\Channel\Exception\SendingMessageFailed; |
8
|
|
|
|
9
|
|
|
final class SimpleMailer implements Mailer |
10
|
|
|
{ |
11
|
|
|
private const MESSAGE_LINE_CHARACTERS_LIMIT = 70; |
12
|
|
|
|
13
|
|
|
/** @var callable|null */ |
14
|
|
|
private $handler; |
15
|
|
|
|
16
|
|
|
/** @var EmailMessage */ |
17
|
|
|
private $message; |
18
|
|
|
|
19
|
1 |
|
public function __construct(callable $handler = null) |
20
|
|
|
{ |
21
|
1 |
|
$this->handler = $handler; |
22
|
1 |
|
} |
23
|
|
|
|
24
|
1 |
|
public function send(EmailMessage $message): void |
25
|
|
|
{ |
26
|
1 |
|
$this->message = $message; |
27
|
|
|
|
28
|
1 |
|
$status = call_user_func( |
29
|
1 |
|
$this->handler ?? 'mail', |
30
|
1 |
|
$this->buildTo(), |
31
|
1 |
|
$this->buildSubject(), |
32
|
1 |
|
$this->buildMessage(), |
33
|
1 |
|
$this->buildMailHeaders() |
34
|
|
|
); |
35
|
|
|
|
36
|
1 |
|
if (!$status) { |
37
|
|
|
$error = error_get_last(); |
38
|
|
|
throw new SendingMessageFailed($error['message'] ?? 'Email has not been accepted for delivery'); |
39
|
|
|
} |
40
|
1 |
|
} |
41
|
|
|
|
42
|
1 |
|
private function buildTo(): string |
43
|
|
|
{ |
44
|
1 |
|
$toList = []; |
45
|
|
|
|
46
|
1 |
|
foreach ($this->message->to as $to) { |
47
|
1 |
|
[$email, $name] = $to; |
|
|
|
|
48
|
|
|
|
49
|
1 |
|
$toList[] = (null !== $name) ? $name . ' <' . $email . '>' : $email; |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
return implode(',', $toList); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
private function buildSubject(): string |
56
|
|
|
{ |
57
|
1 |
|
return $this->message->subject; |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
private function buildMessage(): string |
61
|
|
|
{ |
62
|
1 |
|
return wordwrap($this->message->body, self::MESSAGE_LINE_CHARACTERS_LIMIT); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
private function buildMailHeaders(): string |
66
|
|
|
{ |
67
|
1 |
|
$headers = 'Content-type: ' . $this->message->contentType . '; charset=utf-8' . "\r\n"; |
68
|
|
|
|
69
|
1 |
|
if ($this->message->contentType === 'text/html') { |
70
|
|
|
$headers .= "MIME-Version: 1.0\r\n"; |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
if (null !== $this->message->from) { |
74
|
1 |
|
$headers .= 'From: ' . $this->message->from[0] . "\r\n"; |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
return $headers; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.