123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- <?php
-
-
-
-
-
- class Swift_Plugins_ThrottlerPlugin
- extends Swift_Plugins_BandwidthMonitorPlugin
- implements Swift_Plugins_Sleeper, Swift_Plugins_Timer
- {
-
-
- const BYTES_PER_MINUTE = 0x01;
-
-
- const MESSAGES_PER_MINUTE = 0x10;
-
-
-
- private $_sleeper;
-
-
-
- private $_timer;
-
-
-
- private $_start;
-
-
-
- private $_rate;
-
-
-
- private $_mode;
-
-
-
- private $_messages = 0;
-
-
-
- public function __construct($rate, $mode = self::BYTES_PER_MINUTE,
- Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null)
- {
- $this->_rate = $rate;
- $this->_mode = $mode;
- $this->_sleeper = $sleeper;
- $this->_timer = $timer;
- }
-
-
-
- public function beforeSendPerformed(Swift_Events_SendEvent $evt)
- {
- $time = $this->getTimestamp();
- if (!isset($this->_start))
- {
- $this->_start = $time;
- }
- $duration = $time - $this->_start;
-
- if (self::BYTES_PER_MINUTE == $this->_mode)
- {
- $sleep = $this->_throttleBytesPerMinute($duration);
- }
- else
- {
- $sleep = $this->_throttleMessagesPerMinute($duration);
- }
-
- if ($sleep > 0)
- {
- $this->sleep($sleep);
- }
- }
-
-
-
- public function sendPerformed(Swift_Events_SendEvent $evt)
- {
- parent::sendPerformed($evt);
- ++$this->_messages;
- }
-
-
-
- public function sleep($seconds)
- {
- if (isset($this->_sleeper))
- {
- $this->_sleeper->sleep($seconds);
- }
- else
- {
- sleep($seconds);
- }
- }
-
-
-
- public function getTimestamp()
- {
- if (isset($this->_timer))
- {
- return $this->_timer->getTimestamp();
- }
- else
- {
- return time();
- }
- }
-
-
-
-
-
- private function _throttleBytesPerMinute($timePassed)
- {
- $expectedDuration = $this->getBytesOut() / ($this->_rate / 60);
- return (int) ceil($expectedDuration - $timePassed);
- }
-
-
-
- private function _throttleMessagesPerMinute($timePassed)
- {
- $expectedDuration = $this->_messages / ($this->_rate / 60);
- return (int) ceil($expectedDuration - $timePassed);
- }
-
- }
|