-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathEmailQueueTable.php
More file actions
executable file
·211 lines (190 loc) · 6.36 KB
/
EmailQueueTable.php
File metadata and controls
executable file
·211 lines (190 loc) · 6.36 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<?php
declare(strict_types=1);
namespace EmailQueue\Model\Table;
use Cake\Core\Configure;
use Cake\Database\Expression\QueryExpression;
use Cake\Database\Schema\TableSchemaInterface;
use Cake\Database\Type;
use Cake\I18n\FrozenTime;
use Cake\ORM\Table;
use EmailQueue\Database\Type\JsonType;
use EmailQueue\Database\Type\SerializeType;
use LengthException;
/**
* EmailQueue Table.
*/
class EmailQueueTable extends Table
{
public const MAX_TEMPLATE_LENGTH = 100;
/**
* {@inheritdoc}
*/
public function initialize(array $config = []): void
{
Type::map('email_queue.json', JsonType::class);
Type::map('email_queue.serialize', SerializeType::class);
$this->addBehavior(
'Timestamp',
[
'events' => [
'Model.beforeSave' => [
'created' => 'new',
'modified' => 'always',
],
],
]
);
}
/**
* Stores a new email message in the queue.
*
* @param mixed $to email or array of emails as recipients
* @param array $data associative array of variables to be passed to the email template
* @param array $options list of options for email sending. Possible keys:
*
* - subject : Email's subject
* - cc: array of carbon copy
* - bcc: array of blind carbon copy
* - send_at : date time sting representing the time this email should be sent at (in UTC)
* - template : the name of the element to use as template for the email message
* - layout : the name of the layout to be used to wrap email message
* - format: Type of template to use (html, text or both)
* - config : the name of the email config to be used for sending
*
* @throws \Exception any exception raised in transactional callback
* @throws \LengthException If `template` option length is greater than maximum allowed length
* @return bool
*/
public function enqueue($to, array $data, array $options = []): bool
{
if (array_key_exists('template', $options) && strlen($options['template']) > self::MAX_TEMPLATE_LENGTH) {
throw new LengthException('`template` length must be less or equal to ' . self::MAX_TEMPLATE_LENGTH);
}
$defaults = [
'subject' => '',
'cc' => '',
'bcc' => '',
'send_at' => new FrozenTime('now'),
'template' => 'default',
'layout' => 'default',
'theme' => '',
'format' => 'both',
'headers' => [],
'template_vars' => $data,
'config' => 'default',
'attachments' => [],
];
$email = $options + $defaults;
if (!is_array($to)) {
$to = [$to];
}
$emails = [];
foreach ($to as $t) {
$emails[] = ['email' => $t] + $email;
}
$emails = $this->newEntities($emails);
return $this->getConnection()->transactional(function () use ($emails) {
$failure = collection($emails)
->map(function ($email) {
return $this->save($email);
})
->contains(false);
return !$failure;
});
}
/**
* Returns a list of queued emails that needs to be sent.
*
* @param int|string $size number of unset emails to return
* @throws \Exception any exception raised in transactional callback
* @return array list of unsent emails
*/
public function getBatch($size = 10): array
{
return $this->getConnection()->transactional(function () use ($size) {
$emails = $this->find()
->where([
$this->aliasField('sent') => false,
$this->aliasField('send_tries') . ' <=' => 3,
$this->aliasField('send_at') . ' <=' => new FrozenTime('now'),
$this->aliasField('locked') => false,
])
->limit($size)
->order([$this->aliasField('created') => 'ASC']);
$emails
->extract('id')
->through(function (\Cake\Collection\CollectionInterface $ids) {
if (!$ids->isEmpty()) {
$this->updateAll(['locked' => true], ['id IN' => $ids->toList()]);
}
return $ids;
});
return $emails->toList();
});
}
/**
* Releases locks for all emails in $ids.
*
* @param array|\Traversable $ids The email ids to unlock
*
* @return void
*/
public function releaseLocks($ids): void
{
$this->updateAll(['locked' => false], ['id IN' => $ids]);
}
/**
* Releases locks for all emails in queue, useful for recovering from crashes.
*
* @return void
*/
public function clearLocks(): void
{
$this->updateAll(['locked' => false], '1=1');
}
/**
* Marks an email from the queue as sent.
*
* @param string $id queued email id
* @return void
*/
public function success($id): void
{
$this->updateAll(['sent' => true], ['id' => $id]);
}
/**
* Marks an email from the queue as failed, and increments the number of tries.
*
* @param string $id queued email id
* @param string $error message
* @return void
*/
public function fail($id, $error = null): void
{
$this->updateAll(
[
'send_tries' => new QueryExpression('send_tries + 1'),
'error' => $error,
],
[
'id' => $id,
]
);
}
/**
* Sets the column type for template_vars and headers to json.
*
* @param \Cake\Database\Schema\TableSchemaInterface $schema The table description
* @return \Cake\Database\Schema\TableSchema
*/
protected function _initializeSchema(TableSchemaInterface $schema): TableSchemaInterface
{
$type = Configure::read('EmailQueue.serialization_type') ?: 'email_queue.serialize';
$schema->setColumnType('template_vars', $type);
$schema->setColumnType('headers', $type);
$schema->setColumnType('attachments', $type);
$schema->setColumnType('cc', $type);
$schema->setColumnType('bcc', $type);
return $schema;
}
}