|
<?php |
|
|
|
namespace Acme\Bundle\NewsletterBundle\Manager; |
|
|
|
use Symfony\Component\HttpFoundation\Session\Session; |
|
|
|
class NewsletterManager |
|
{ |
|
/** |
|
* @var \Swift_Mailer |
|
*/ |
|
private $mailer; |
|
|
|
/** |
|
* @var array |
|
*/ |
|
private $recipients; |
|
|
|
/** |
|
* @var Session |
|
*/ |
|
private $session; |
|
|
|
/** |
|
* @var string |
|
*/ |
|
private $mailFrom; |
|
|
|
/** |
|
* @param \Swift_Mailer $mailer |
|
*/ |
|
public function __construct(\Swift_Mailer $mailer, Session $session) |
|
{ |
|
$this->mailer = $mailer; |
|
$this->session = $session; |
|
|
|
// load recipients |
|
$this->recipients = []; |
|
if ($session->has('newsletter_recipients')) { |
|
$this->recipients = $session->get('newsletter_recipients'); |
|
} |
|
|
|
// this should actually be set in config |
|
$this->mailFrom = '[email protected]'; |
|
} |
|
|
|
/** |
|
* Subscribes a recipient for newsletter. |
|
* |
|
* @param string $emailAddress |
|
* |
|
* @return bool |
|
*/ |
|
public function subscribe($emailAddress) |
|
{ |
|
if (array_search($emailAddress, $this->recipients) === false) { |
|
$this->recipients[] = $emailAddress; |
|
$this->session->set('newsletter_recipients', $this->recipients); |
|
|
|
return true; |
|
} |
|
|
|
return false; |
|
} |
|
|
|
/** |
|
* Unsubscribes recipient from newsletter. |
|
* |
|
* @param string $emailAddress |
|
* |
|
* @return bool |
|
*/ |
|
public function unsubscribe($emailAddress) |
|
{ |
|
$index = array_search($emailAddress, $this->recipients); |
|
if ($index !== false) { |
|
unset($this->recipients[$index]); |
|
$this->session->set('newsletter_recipients', $this->recipients); |
|
|
|
return true; |
|
} |
|
|
|
return false; |
|
} |
|
|
|
/** |
|
* Sends a newsletter message to all registered recipients. |
|
* |
|
* @param string $subjectString |
|
* @param string $messageString |
|
*/ |
|
public function sendNewsletter($subjectString, $messageString) |
|
{ |
|
// send mail to each subscribed email |
|
foreach ($this->getRecipients() as $recipient) { |
|
$message = new \Swift_Message($subjectString, $messageString); |
|
$message->setFrom($this->mailFrom); |
|
$message->setTo($recipient); |
|
$this->mailer->send($message); |
|
} |
|
} |
|
|
|
/** |
|
* Return all recipients of a newsletter. |
|
* |
|
* @return array |
|
*/ |
|
private function getRecipients() |
|
{ |
|
return $this->recipients; |
|
} |
|
} |