Skip to content

Instantly share code, notes, and snippets.

@ricbra
Created June 30, 2015 09:52
Show Gist options
  • Save ricbra/ee87d0a25db708ec83df to your computer and use it in GitHub Desktop.
Save ricbra/ee87d0a25db708ec83df to your computer and use it in GitHub Desktop.
<?php
/*
* (c) Waarneembemiddeling.nl
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Wb\Bundle\CoreBundle\SwiftMailer;
use igorw\FailingTooHardException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FailsafeQueueFlusher
{
private $attempts = 0;
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function flushQueue(
$retryAttempts,
\Swift_Spool $spool,
\Swift_Transport $transport
) {
$attempts = &$this->attempts;
$attempts = 0;
try {
\igorw\retry($retryAttempts, function () use ($spool, $transport, $logger, &$attempts) {
$this->logger->info(sprintf(
'Start attempt %d for sending message..',
$attempts+1
));
try {
$attempts++;
$spool->flushQueue($transport);
} catch (\Swift_TransportException $e) {
$this->logger->warning(sprintf(
'Exception occured during sending: %s',
$e->getMessage()
));
try {
// Hard disconnect here to clean up.
$spool->stop();
$spool->start();
} catch (\Swift_TransportException $e) {
// Do nothing.
}
// Throw $e again so igorw\retry kicks in
throw $e;
}
});
} catch (FailingTooHardException $e) {
// This will popup in logentries
$this->logger->critical(sprintf(
'Failed permanently sending messing: %s',
$e->getPrevious()->getMessage()
));
return false;
}
return true;
}
public function getMailer(ContainerInterface $container, $mailerId)
{
$serviceMailer = sprintf('swiftmailer.mailer.%s', $mailerId);
if (! $container->has($serviceMailer)) {
throw new \InvalidArgumentException(sprintf('Nonexisting mailer id "%s" given', $mailerId));
}
return $container->get($serviceMailer);
}
public function getAttempts()
{
return $this->attempts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment