Reduce complexity in MailOutput.

This commit is contained in:
Markus Birth 2016-07-10 23:01:21 +02:00
parent 02c6c15548
commit f94186a20f

View File

@ -7,6 +7,7 @@ use \Frs\Output\GenericOutput;
class MailOutput extends GenericOutput
{
private $recipients = array();
private $headers = array();
private $subject = '';
/**
@ -36,6 +37,55 @@ class MailOutput extends GenericOutput
$this->subject = $newSubject;
}
/**
* Sets the given header $key to $value. A Subject: header sets
* the subject via $this->setSubject(). A To: header is ignored.
*
* @param string $key Header name
* @param string $value Header contents
*/
public function setHeader($key, $value)
{
if (strtolower($key) == 'subject') {
$this->setSubject($value);
return;
}
if (strtolower($key) == 'to') {
// ignore for now (maybe set as recipient?)
return;
}
$this->headers[$key] = $value;
}
/**
* Returns a header section (as string) of all currently set headers.
*
* @return string Header section.
*/
public function getHeaders()
{
$all_headers = '';
foreach ($this->headers as $key=>$value) {
$all_headers .= $key . ': ' . $value . "\r\n";
}
return $all_headers;
}
/**
* Sets mail headers. If headers contain a Subject: line, the subject is set from that.
*
* @param string $headers All mail headers separated by newlines (CRLF or LF).
*/
public function setHeadersFromString($headers)
{
$header_lines = preg_split('/\r?\n/', $headers);
foreach ($header_lines as $header_line) {
list($key, $value) = preg_split('/: /', $header_line, 2);
$this->setHeader($key, $value);
}
}
/**
* Sends the prepared mail
*
@ -45,24 +95,10 @@ class MailOutput extends GenericOutput
{
$mail_html = $this->getRenderedOutput(); // contains headers + body
list($headers, $mailbody) = preg_split('/\r?\n\r?\n/', $mail_html, 2);
$header_lines = preg_split('/\r?\n/', $headers);
$header_filtered = '';
foreach ($header_lines as $header_line) {
list($key, $value) = preg_split('/: /', $header_line, 2);
if (in_array(strtolower($key), array('subject', 'to'))) {
// Skip Subject and To headers as they're added by PHP
if (strtolower($key) == 'subject') {
$this->setSubject($value);
}
continue;
}
$header_filtered .= $header_line . "\r\n";
}
$this->setHeadersFromString($headers);
$recipients = implode(', ', $this->recipients);
// TODO: Check if any recipients in the first place
$mail_sent = mail($recipients, $this->subject, $mailbody, $header_filtered);
$mail_sent = mail($recipients, $this->subject, $mailbody, $this->getHeaders());
return $mail_sent;
}
}