1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace ICanBoogie\Mailer;
13
14 use ICanBoogie\PropertyNotDefined;
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 class Message extends MessagePart
46 {
47 static = [
48
49 'from' => 'From',
50 'to' => 'To',
51 'cc' => 'Cc',
52 'bcc' => 'Bcc'
53
54 ];
55
56 static public function from($source)
57 {
58 if ($source instanceof self)
59 {
60 return $source;
61 }
62
63 if (!is_array($source))
64 {
65 throw new \InvalidArgumentException("\$source must either be a Message instance or an array.");
66 }
67
68 $header_fields = [];
69
70 if (isset($source['header']))
71 {
72
73
74 $header_fields = $source['header'];
75
76 unset($source['header']);
77 }
78
79 return new static($source, $header_fields);
80 }
81
82 83 84 85 86
87 public $subject;
88
89 protected $parts;
90 protected $attachments;
91
92 public function __construct(array $attributes=[], array $header_fields=[])
93 {
94 $body = isset($attributes['body']) ? $attributes['body'] : '';
95
96 parent::__construct($body, $header_fields + [ 'Content-Type' => 'text/plain; charset=UTF-8' ]);
97
98 foreach ($attributes as $attribute => $value)
99 {
100 switch ($attribute)
101 {
102 case 'bcc':
103 case 'cc':
104 case 'from':
105 case 'subject':
106 case 'type':
107 case 'to':
108
109 $this->$attribute = $value;
110
111 break;
112
113 case 'body':
114 break;
115
116 default:
117
118 throw new PropertyNotDefined([ $attribute, $this ]);
119 }
120 }
121 }
122
123 public function __get($property)
124 {
125 switch ($property)
126 {
127 case 'bcc':
128 case 'cc':
129 case 'from':
130 case 'to':
131
132 return $this->header[self::$property_to_header[$property]];
133 }
134
135 return parent::__get($property);
136 }
137
138 public function __set($property, $value)
139 {
140 switch ($property)
141 {
142 case 'bcc':
143 case 'cc':
144 case 'from':
145 case 'to':
146
147 $this->header[self::$property_to_header[$property]] = $value;
148
149 return;
150
151 case 'type':
152
153 $this->header['Content-Type']->type = "text/{$value}";
154
155 return;
156 }
157
158 parent::__set($property, $value);
159 }
160
161 public function __toString()
162 {
163 return $this->body;
164 }
165
166 167 168 169 170 171 172
173 public function prepare()
174 {
175 $subject = (string) $this->subject;
176 $charset = mb_detect_encoding($subject);
177
178 if ($charset != 'ASCII')
179 {
180 $subject = mb_convert_encoding($subject, 'UTF-8');
181 $subject = mb_encode_mimeheader($subject, 'UTF-8');
182 }
183
184 $header = clone $this->header;
185
186 unset($header['To']);
187 unset($header['Subject']);
188
189 return [ (string) $this->to, $subject, (string) $this, (string) $header ];
190 }
191 }