Skip to content

Instantly share code, notes, and snippets.

@holantomas
Created October 3, 2018 13:48
Show Gist options
  • Save holantomas/37d1b2d8e5e7217ff19e5343f50932cd to your computer and use it in GitHub Desktop.
Save holantomas/37d1b2d8e5e7217ff19e5343f50932cd to your computer and use it in GitHub Desktop.
FallbackMailer
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Mail;
use Nette;
class FallbackMailer implements IMailer
{
use Nette\SmartObject;
/** @var callable[] function (FallbackMailer $sender, SendException $e, IMailer $mailer, Message $mail) */
public $onFailure;
/** @var IMailer[] */
private $mailers;
/** @var int */
private $retryCount;
/** @var int in miliseconds */
private $retryWaitTime;
/**
* @param int $retryWaitTime in miliseconds
* @param IMailer[] $mailers
*/
public function __construct(int $retryCount = 3, int $retryWaitTime = 1000, IMailer ... $mailers)
{
$this->mailers = $mailers;
$this->retryCount = $retryCount;
$this->retryWaitTime = $retryWaitTime;
}
/**
* Sends email.
* @throws FallbackMailerException
*/
public function send(Message $mail): void
{
if (!$this->mailers) {
throw new Nette\InvalidArgumentException('At least one mailer must be provided.');
}
for ($i = 0; $i < $this->retryCount; $i++) {
if ($i > 0) {
usleep($this->retryWaitTime * 1000);
}
foreach ($this->mailers as $mailer) {
try {
$mailer->send($mail);
return;
} catch (SendException $e) {
$failures[] = $e;
$this->onFailure($this, $e, $mailer, $mail);
}
}
}
$e = new FallbackMailerException('All mailers failed to send the message.');
$e->failures = $failures;
throw $e;
}
/**
* @return static
*/
public function addMailer(IMailer $mailer)
{
$this->mailers[] = $mailer;
return $this;
}
}
<?php
declare(strict_types=1);
$mailers = [];
// fill $mailers with IMailer instances
$fm = new \Nette\Mail\FallbackMailer(3, 1000, ... $mailers);
// OR
$fm = new \Nette\Mail\FallbackMailer(3, 1000, $mailer1, $mailer2, $mailer3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment