Created
March 20, 2020 17:36
-
-
Save abramovantonru/0495e5876d7e244c0c0a0a26b975db89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
use Swift_Events_SendEvent; | |
use Swift_Events_SendListener; | |
use Swift_Plugins_Sleeper; | |
/** | |
* Plugin for fix timeout errors on sending mails from message queue (rabbitMQ) with persistent connection to SMTP server | |
*/ | |
class Swift_Plugins_Timeout_Plugin implements Swift_Events_SendListener, Swift_Plugins_Sleeper | |
{ | |
/** | |
* Max seconds for delay before restarting Transport. | |
* | |
* @var int | |
*/ | |
private $timeout; | |
/** | |
* The number of seconds to sleep for during a restart. | |
* | |
* @var int | |
*/ | |
private $sleep; | |
/** | |
* The internal timestamp of last use Transport. | |
* | |
* @var int | |
*/ | |
private $last = 0; | |
/** | |
* The Sleeper instance for sleeping. | |
* | |
* @var Swift_Plugins_Sleeper | |
*/ | |
private $sleeper; | |
/** | |
* @param int $timeout | |
* @param int $sleep time | |
* @param Swift_Plugins_Sleeper $sleeper (not needed really) | |
*/ | |
public function __construct(int $timeout = 60, int $sleep = 0, Swift_Plugins_Sleeper $sleeper = null) | |
{ | |
$this->setTimeout($timeout); | |
$this->setSleepTime($sleep); | |
$this->sleeper = $sleeper; | |
} | |
public function setTimeout($timeout) | |
{ | |
$this->timeout = $timeout; | |
} | |
public function setSleepTime($sleep) | |
{ | |
$this->sleep = $sleep; | |
} | |
/** | |
* Invoked immediately before the Message is sent. | |
* @param Swift_Events_SendEvent $evt | |
*/ | |
public function beforeSendPerformed(Swift_Events_SendEvent $evt) | |
{ | |
if ($this->last && $this->last + $this->timeout <= time()) { | |
$transport = $evt->getTransport(); | |
$transport->stop(); | |
if ($this->sleep) { | |
$this->sleep($this->sleep); | |
} | |
$transport->start(); | |
$this->last = 0; | |
} | |
} | |
/** | |
* Invoked immediately after the Message is sent. | |
* @param Swift_Events_SendEvent $evt | |
*/ | |
public function sendPerformed(Swift_Events_SendEvent $evt) | |
{ | |
$this->last = time(); | |
} | |
/** | |
* Sleep for $seconds. | |
* | |
* @param int $seconds | |
*/ | |
public function sleep($seconds): void | |
{ | |
if (isset($this->sleeper)) { | |
$this->sleeper->sleep($seconds); | |
} else { | |
sleep($seconds); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment