PluginProbe
SendWP / 0.0.2
SendWP v0.0.2
trunk 0.0.1 0.0.2 0.0.3 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.1 1.2.10 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3 1.3.1 1.4.4 1.4.5 1.4.6 1.4.8
sendwp / includes / class.mailer.php

class.mailer.php in SendWP 0.0.2, at includes/class.mailer.php

107 lines 2.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace SendWP;
4
5 use SendWP\API\Request;
6
7 /**
8 * A decorater for sending API based transactional email.
9 *
10 * @TODO Maybe extract formatting methods.
11 */
12 class Mailer implements MailerInterface
13 {
14 protected $phpmailer;
15 protected $request;
16
17 public static function factory(&$phpmailer)
18 {
19 $request = \SendWP\API\Request::create('postmaster');
20 $phpmailer = new self($phpmailer, $request);
21 return $phpmailer;
22 }
23
24 public function __construct($phpmailer, Request $request)
25 {
26 $this->phpmailer = $phpmailer;
27 $this->request = $request;
28 }
29
30 /**
31 * Check for property/method in $phpmailer.
32 */
33 public function __get($name)
34 {
35 if (property_exists($this->phpmailer, $name)) {
36 return $this->phpmailer->$name;
37 }
38 return '';
39 }
40
41 public function __call($name, $arguments)
42 {
43 if (method_exists($this->phpmailer, $name)) {
44 return call_user_func([ $this->phpmailer, $name ], $arguments);
45 }
46 return null;
47 }
48
49 public function getAttachments()
50 {
51 $attachments = $this->phpmailer->getAttachments();
52
53 // Format the attachments, per service requirement.
54 $attachments = array_map([ $this, 'formatAttachment' ], $attachments);
55
56 return $attachments;
57 }
58
59 public function send()
60 {
61 $to_emails = array_map([ $this, 'formatEmails' ], $this->getToAddresses());
62 $cc_emails = array_map([ $this, 'formatEmails' ], $this->getCcAddresses());
63 $bcc_emails = array_map([ $this, 'formatEmails' ], $this->getBccAddresses());
64
65 $args = [
66 'body' => [
67 'to' => json_encode( (array) $to_emails ),
68 'from' => $this->From,
69 'from_name' => $this->FromName,
70 'subject' => $this->Subject,
71 'body' => $this->Body,
72 'altbody' => $this->AltBody,
73 ],
74 ];
75
76 if( ! empty( $cc_emails ) ) {
77 $args[ 'body' ][ 'cc' ] = json_encode( (array) $cc_emails );
78 }
79
80 if( ! empty( $bcc_emails ) ) {
81 $args[ 'body' ][ 'bcc' ] = json_encode( (array) $bcc_emails );
82 }
83
84 if ($attachments = $this->getAttachments()) {
85 $args[ 'body' ][ 'attachments' ] = $attachments;
86 }
87
88 // Response is empty...
89 $response = $this->request->post($args);
90
91 return true; // Sent by the Service.
92 }
93
94 protected function formatEmails($emails)
95 {
96 return reset($emails);
97 }
98
99 protected function formatAttachment($attachment)
100 {
101 return [
102 'filename' => $attachment[1], // $filename per PHPMailer docs.
103 'filedata' => file_get_contents($attachment[0]) // $path per PHPMailer docs.
104 ];
105 }
106 }
107