1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Genkgo\Mail\Transport; |
5
|
|
|
|
6
|
|
|
use Genkgo\Mail\Exception\AbstractProtocolException; |
7
|
|
|
use Genkgo\Mail\Exception\QueueIfFailedException; |
8
|
|
|
use Genkgo\Mail\Exception\QueueStoreException; |
9
|
|
|
use Genkgo\Mail\Header\GenericHeader; |
10
|
|
|
use Genkgo\Mail\MessageInterface; |
11
|
|
|
use Genkgo\Mail\Queue\QueueInterface; |
12
|
|
|
use Genkgo\Mail\TransportInterface; |
13
|
|
|
|
14
|
|
|
final class QueueIfFailedTransport implements TransportInterface |
15
|
|
|
{ |
16
|
|
|
public const QUEUED_HEADER = 'X-Queued-At'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var array|TransportInterface[] |
20
|
|
|
*/ |
21
|
|
|
private $transports; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var array|QueueInterface[] |
25
|
|
|
*/ |
26
|
|
|
private $queueStorage; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var bool |
30
|
|
|
*/ |
31
|
|
|
private $useQueue = false; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param TransportInterface[] $transports |
35
|
|
|
* @param QueueInterface[] $queueStorage |
36
|
|
|
*/ |
37
|
5 |
|
public function __construct(array $transports, array $queueStorage) |
38
|
|
|
{ |
39
|
5 |
|
$this->transports = $transports; |
40
|
5 |
|
$this->queueStorage = $queueStorage; |
41
|
5 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param MessageInterface $message |
45
|
|
|
* @throws QueueIfFailedException |
46
|
|
|
*/ |
47
|
5 |
|
public function send(MessageInterface $message): void |
48
|
|
|
{ |
49
|
5 |
|
if ($this->useQueue === false) { |
50
|
5 |
|
foreach ($this->transports as $sender) { |
51
|
|
|
try { |
52
|
5 |
|
$sender->send($message); |
53
|
1 |
|
return; |
54
|
5 |
|
} catch (AbstractProtocolException $e) { |
|
|
|
|
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
// switch later deliveries with this transport directly to queue |
60
|
4 |
|
if ($this->useQueue === false) { |
61
|
4 |
|
$this->useQueue = true; |
62
|
|
|
} |
63
|
|
|
|
64
|
4 |
|
foreach ($this->queueStorage as $storage) { |
65
|
|
|
try { |
66
|
4 |
|
if (!$message->hasHeader(self::QUEUED_HEADER)) { |
67
|
4 |
|
$message = $message->withHeader( |
68
|
4 |
|
new GenericHeader( |
69
|
4 |
|
self::QUEUED_HEADER, |
70
|
4 |
|
(new \DateTimeImmutable('now'))->format('r') |
71
|
|
|
) |
72
|
|
|
); |
73
|
|
|
} |
74
|
|
|
|
75
|
4 |
|
$storage->store($message); |
76
|
3 |
|
return; |
77
|
2 |
|
} catch (QueueStoreException $e) { |
|
|
|
|
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
1 |
|
throw new QueueIfFailedException('Cannot send nor queue this e-mail message'); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|