1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Genkgo\Mail\Queue; |
5
|
|
|
|
6
|
|
|
use Genkgo\Mail\Exception\EmptyQueueException; |
7
|
|
|
use Genkgo\Mail\GenericMessage; |
8
|
|
|
use Genkgo\Mail\MessageInterface; |
9
|
|
|
|
10
|
|
|
final class FilesystemQueue implements QueueInterface, \Countable |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
private $directory; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var int |
19
|
|
|
*/ |
20
|
|
|
private $mode; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param string $directory |
24
|
|
|
* @param int $mode |
25
|
|
|
*/ |
26
|
4 |
|
public function __construct(string $directory, int $mode = 0750) |
27
|
|
|
{ |
28
|
4 |
|
$this->directory = $directory; |
29
|
4 |
|
$this->mode = $mode; |
30
|
4 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param MessageInterface $message |
34
|
|
|
*/ |
35
|
4 |
|
public function store(MessageInterface $message): void |
36
|
|
|
{ |
37
|
4 |
|
$messageString = (string)$message; |
38
|
4 |
|
$filename = \hash('sha256', $messageString) . '.eml'; |
39
|
|
|
|
40
|
4 |
|
\file_put_contents( |
41
|
4 |
|
$this->directory . '/' . $filename, |
42
|
4 |
|
$messageString |
43
|
|
|
); |
44
|
|
|
|
45
|
4 |
|
\chmod($this->directory . '/' . $filename, $this->mode); |
46
|
4 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return MessageInterface |
50
|
|
|
* @throws EmptyQueueException |
51
|
|
|
*/ |
52
|
2 |
|
public function fetch(): MessageInterface |
53
|
|
|
{ |
54
|
2 |
|
$queue = new \GlobIterator($this->directory . '/*.eml'); |
55
|
|
|
/** @var \SplFileInfo $item */ |
56
|
2 |
|
foreach ($queue as $item) { |
57
|
2 |
|
$messageString = \file_get_contents($item->getPathname()); |
58
|
2 |
|
if ($messageString === false) { |
59
|
|
|
throw new \UnexpectedValueException('Cannot fetch message from file'); |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
\unlink($item->getPathname()); |
63
|
2 |
|
return GenericMessage::fromString($messageString); |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
throw new EmptyQueueException('No message left in queue'); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return int |
71
|
|
|
*/ |
72
|
1 |
|
public function count(): int |
73
|
|
|
{ |
74
|
1 |
|
return (new \GlobIterator($this->directory . '/*.eml'))->count(); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|