Total Complexity | 65 |
Total Lines | 380 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like SparkPostApiTransport often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SparkPostApiTransport, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
31 | class SparkPostApiTransport extends AbstractApiTransport |
||
32 | { |
||
33 | private const HOST = 'api.sparkpost.com'; |
||
34 | private const EU_HOST = 'api.eu.sparkpost.com'; |
||
35 | |||
36 | /** |
||
37 | * @var SparkPostApiClient |
||
38 | */ |
||
39 | private $apiClient; |
||
40 | |||
41 | private $apiResult; |
||
42 | |||
43 | public function __construct(SparkPostApiClient $apiClient, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null) |
||
44 | { |
||
45 | $this->apiClient = $apiClient; |
||
46 | |||
47 | if ($apiClient->getEuEndpoint()) { |
||
48 | $this->setHost(self::EU_HOST); |
||
49 | } else { |
||
50 | $this->setHost(self::HOST); |
||
51 | } |
||
52 | |||
53 | parent::__construct($client, $dispatcher, $logger); |
||
54 | } |
||
55 | |||
56 | public function __toString(): string |
||
57 | { |
||
58 | return sprintf('sparkpost+api://%s', $this->getEndpoint()); |
||
59 | } |
||
60 | |||
61 | protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $envelope): ResponseInterface |
||
62 | { |
||
63 | $disableSending = $email->getHeaders()->has('X-SendingDisabled') || !SparkPostHelper::getSendingEnabled(); |
||
64 | |||
65 | // We don't really care about the actual response |
||
66 | $response = new MockResponse(); |
||
67 | |||
68 | $to = $email->getTo(); |
||
69 | |||
70 | if ($disableSending) { |
||
71 | $result = [ |
||
72 | 'total_rejected_recipients' => 0, |
||
73 | 'total_accepted_recipients' => count($to), |
||
74 | 'id' => uniqid(), |
||
75 | 'disabled' => true, |
||
76 | ]; |
||
77 | } else { |
||
78 | $payload = $this->getPayload($email, $envelope); |
||
79 | $result = $this->apiClient->createTransmission($payload); |
||
80 | } |
||
81 | |||
82 | // Add email |
||
83 | $result['email'] = implode('; ', array_map(function ($recipient) { |
||
84 | return $recipient->toString(); |
||
85 | }, $to)); |
||
86 | |||
87 | $this->apiResult = $result; |
||
88 | |||
89 | $messageId = $result['id'] ?? null; |
||
90 | if ($messageId) { |
||
91 | $sentMessage->setMessageId($messageId); |
||
92 | } |
||
93 | |||
94 | if (SparkPostHelper::getLoggingEnabled()) { |
||
95 | $this->logMessageContent($email, $result); |
||
96 | } |
||
97 | |||
98 | return $response; |
||
99 | } |
||
100 | |||
101 | public function getApiResult(): array |
||
102 | { |
||
103 | return $this->apiResult; |
||
104 | } |
||
105 | |||
106 | private function getEndpoint(): ?string |
||
107 | { |
||
108 | return ($this->host ?: self::HOST) . ($this->port ? ':' . $this->port : ''); |
||
109 | } |
||
110 | |||
111 | private function buildAttachments(Email $email): array |
||
112 | { |
||
113 | $result = []; |
||
114 | foreach ($email->getAttachments() as $attachment) { |
||
115 | /** @var ParameterizedHeader $file */ |
||
116 | $file = $attachment->getPreparedHeaders()->get('Content-Disposition'); |
||
117 | /** @var ParameterizedHeader $type */ |
||
118 | $type = $attachment->getPreparedHeaders()->get('Content-Type'); |
||
119 | |||
120 | $result[] = [ |
||
121 | 'name' => $file->getParameter('filename'), |
||
122 | 'type' => $type->getValue(), |
||
123 | 'data' => base64_encode($attachment->getBody()), |
||
124 | ]; |
||
125 | } |
||
126 | |||
127 | return $result; |
||
128 | } |
||
129 | |||
130 | /** |
||
131 | * @param Email $email |
||
132 | * @param Envelope $envelope |
||
133 | * @return array |
||
134 | */ |
||
135 | private function getPayload(Email $email, Envelope $envelope): array |
||
136 | { |
||
137 | $from = $envelope->getSender(); |
||
138 | |||
139 | $fromFirstEmail = $from->getAddress(); |
||
140 | $fromFirstName = $from->getName(); |
||
141 | if (SparkPostHelper::config()->override_admin_email && SparkPostHelper::isAdminEmail($fromFirstEmail)) { |
||
142 | $fromFirstEmail = SparkPostHelper::resolveDefaultFromEmail(); |
||
143 | } |
||
144 | if (SparkPostHelper::getEnvForceSender()) { |
||
145 | $fromFirstEmail = SparkPostHelper::getEnvForceSender(); |
||
146 | } |
||
147 | if (!$fromFirstName) { |
||
148 | $fromFirstName = EmailUtils::get_displayname_from_rfc_email($fromFirstEmail); |
||
149 | } |
||
150 | |||
151 | $toAddresses = []; |
||
152 | $ccAddresses = []; |
||
153 | $bccAddresses = []; |
||
154 | |||
155 | foreach ($envelope->getRecipients() as $recipient) { |
||
156 | $type = 'to'; |
||
157 | if (\in_array($recipient, $email->getBcc(), true)) { |
||
158 | $type = 'bcc'; |
||
159 | } elseif (\in_array($recipient, $email->getCc(), true)) { |
||
160 | $type = 'cc'; |
||
161 | } |
||
162 | |||
163 | $recipientEmail = $recipient->getAddress(); |
||
164 | $recipientName = $recipient->getName(); |
||
165 | if (!$recipientName) { |
||
166 | $recipientName = EmailUtils::get_displayname_from_rfc_email($recipientEmail); |
||
167 | } |
||
168 | |||
169 | switch ($type) { |
||
170 | case 'to': |
||
171 | $toAddresses[$recipientEmail] = $recipientName; |
||
172 | break; |
||
173 | case 'cc': |
||
174 | $ccAddresses[$recipientEmail] = $recipientName; |
||
175 | break; |
||
176 | case 'bcc': |
||
177 | $bccAddresses[$recipientEmail] = $recipientName; |
||
178 | break; |
||
179 | } |
||
180 | } |
||
181 | |||
182 | $recipients = []; |
||
183 | $cc = []; |
||
184 | $bcc = []; |
||
185 | $headers = []; |
||
186 | $tags = []; |
||
187 | $metadata = []; |
||
188 | $inlineCss = null; |
||
189 | |||
190 | // Mandrill compatibility |
||
191 | // Data is merged with transmission and removed from headers |
||
192 | // @link https://mailchimp.com/developer/transactional/docs/tags-metadata/#tags |
||
193 | $emailHeaders = $email->getHeaders(); |
||
194 | if ($emailHeaders->has('X-MC-Tags')) { |
||
195 | $tagsHeader = $emailHeaders->get('X-MC-Tags'); |
||
196 | $tags = explode(',', self::getHeaderValue($tagsHeader)); |
||
197 | $emailHeaders->remove('X-MC-Tags'); |
||
198 | } |
||
199 | if ($emailHeaders->has('X-MC-Metadata')) { |
||
200 | $metadataHeader = $emailHeaders->get('X-MC-Metadata'); |
||
201 | $metadata = json_decode(self::getHeaderValue($metadataHeader), JSON_OBJECT_AS_ARRAY); |
||
|
|||
202 | $emailHeaders->remove('X-MC-Metadata'); |
||
203 | } |
||
204 | if ($emailHeaders->has('X-MC-InlineCSS')) { |
||
205 | $inlineHeader = $emailHeaders->get('X-MC-InlineCSS'); |
||
206 | $inlineCss = self::getHeaderValue($inlineHeader); |
||
207 | $emailHeaders->remove('X-MC-InlineCSS'); |
||
208 | } |
||
209 | |||
210 | // Handle MSYS headers |
||
211 | // Data is merge with transmission and removed from headers |
||
212 | // @link https://developers.sparkpost.com/api/smtp-api.html |
||
213 | $msysHeader = []; |
||
214 | if ($emailHeaders->has('X-MSYS-API')) { |
||
215 | $msysHeaderObj = $emailHeaders->get('X-MSYS-API'); |
||
216 | $msysHeader = json_decode(self::getHeaderValue($msysHeaderObj), JSON_OBJECT_AS_ARRAY); |
||
217 | if (!empty($msysHeader['tags'])) { |
||
218 | $tags = array_merge($tags, $msysHeader['tags']); |
||
219 | } |
||
220 | if (!empty($msysHeader['metadata'])) { |
||
221 | $metadata = array_merge($metadata, $msysHeader['metadata']); |
||
222 | } |
||
223 | $emailHeaders->remove('X-MSYS-API'); |
||
224 | } |
||
225 | |||
226 | // Build recipients list |
||
227 | // @link https://developers.sparkpost.com/api/recipient-lists.html |
||
228 | $primaryEmail = null; |
||
229 | foreach ($toAddresses as $toEmail => $toName) { |
||
230 | if ($primaryEmail === null) { |
||
231 | $primaryEmail = $toEmail; |
||
232 | } |
||
233 | if (!$toName) { |
||
234 | $toName = $toEmail; |
||
235 | } |
||
236 | $recipient = array( |
||
237 | 'address' => array( |
||
238 | 'email' => $toEmail, |
||
239 | 'name' => $toName, |
||
240 | ) |
||
241 | ); |
||
242 | if (!empty($tags)) { |
||
243 | $recipient['tags'] = $tags; |
||
244 | } |
||
245 | // TODO: metadata are not valid? |
||
246 | if (!empty($metadata)) { |
||
247 | $recipient['metadata'] = $metadata; |
||
248 | } |
||
249 | $recipients[] = $recipient; |
||
250 | } |
||
251 | |||
252 | // @link https://www.sparkpost.com/docs/faq/cc-bcc-with-rest-api/ |
||
253 | foreach ($ccAddresses as $ccEmail => $ccName) { |
||
254 | $cc[] = array( |
||
255 | 'email' => $ccEmail, |
||
256 | 'name' => $ccName, |
||
257 | 'header_to' => $primaryEmail ? $primaryEmail : $ccEmail, |
||
258 | ); |
||
259 | } |
||
260 | |||
261 | foreach ($bccAddresses as $bccEmail => $bccName) { |
||
262 | $bcc[] = array( |
||
263 | 'email' => $bccEmail, |
||
264 | 'name' => $bccName, |
||
265 | 'header_to' => $primaryEmail ? $primaryEmail : $ccEmail, |
||
266 | ); |
||
267 | } |
||
268 | |||
269 | $bodyHtml = $email->getHtmlBody(); |
||
270 | $bodyText = $email->getTextBody(); |
||
271 | |||
272 | |||
273 | // If we ask to provide plain, use our custom method instead of the provided one |
||
274 | if ($bodyHtml && SparkPostHelper::config()->provide_plain) { |
||
275 | $bodyText = EmailUtils::convert_html_to_text($bodyHtml); |
||
276 | } |
||
277 | |||
278 | // Should we inline css |
||
279 | if (!$inlineCss && SparkPostHelper::config()->inline_styles) { |
||
280 | $bodyHtml = EmailUtils::inline_styles($bodyHtml); |
||
281 | } |
||
282 | |||
283 | // Custom unsubscribe list |
||
284 | if ($emailHeaders->has('List-Unsubscribe')) { |
||
285 | $unsubHeader = $emailHeaders->get('List-Unsubscribe'); |
||
286 | $headers['List-Unsubscribe'] = self::getHeaderValue($unsubHeader); |
||
287 | } |
||
288 | |||
289 | $defaultParams = SparkPostHelper::config()->default_params; |
||
290 | if ($inlineCss !== null) { |
||
291 | $defaultParams['inline_css'] = $inlineCss; |
||
292 | } |
||
293 | |||
294 | // Build base transmission. Keep in mind that parameters are mapped by the sdk |
||
295 | // @link @link https://developers.sparkpost.com/api/transmissions/#transmissions-post-send-inline-content |
||
296 | $sparkPostMessage = [ |
||
297 | 'recipients' => $recipients, |
||
298 | 'content' => [ |
||
299 | 'from' => [ |
||
300 | 'name' => $fromFirstName, |
||
301 | 'email' => $fromFirstEmail, |
||
302 | ], |
||
303 | 'subject' => $email->getSubject(), |
||
304 | 'html' => $bodyHtml, |
||
305 | 'text' => $bodyText, |
||
306 | ], |
||
307 | ]; |
||
308 | if ($email->getReplyTo()) { |
||
309 | $sparkPostMessage['reply_to'] = $email->getReplyTo(); |
||
310 | } |
||
311 | |||
312 | // Add default params |
||
313 | $sparkPostMessage = array_merge($defaultParams, $sparkPostMessage); |
||
314 | if ($msysHeader) { |
||
315 | $sparkPostMessage = array_merge($sparkPostMessage, $msysHeader); |
||
316 | } |
||
317 | |||
318 | // Add remaining elements |
||
319 | if (!empty($cc)) { |
||
320 | $sparkPostMessage['headers.CC'] = $cc; |
||
321 | } |
||
322 | if (!empty($headers)) { |
||
323 | $sparkPostMessage['customHeaders'] = $headers; |
||
324 | } |
||
325 | |||
326 | $attachments = $this->buildAttachments($email); |
||
327 | if (count($attachments) > 0) { |
||
328 | $sparkPostMessage['attachments'] = $attachments; |
||
329 | } |
||
330 | |||
331 | return $sparkPostMessage; |
||
332 | } |
||
333 | |||
334 | /** |
||
335 | * @param HeaderInterface|UnstructuredHeader|null $header |
||
336 | * @return string |
||
337 | */ |
||
338 | protected static function getHeaderValue(HeaderInterface $header = null) |
||
347 | } |
||
348 | |||
349 | |||
350 | /** |
||
351 | * Log message content |
||
352 | * |
||
353 | * @param Email $message |
||
354 | * @param array $results Results from the api |
||
355 | * @throws Exception |
||
356 | */ |
||
357 | protected function logMessageContent(Email $message, $results = []) |
||
411 | } |
||
412 | } |
||
414 |