TYPO3  7.6
ThrottlerPlugin.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  * This file is part of SwiftMailer.
5  * (c) 2004-2009 Chris Corbyn
6  *
7  * For the full copyright and license information, please view the LICENSE
8  * file that was distributed with this source code.
9  */
10 
17 {
19  const BYTES_PER_MINUTE = 0x01;
20 
22  const MESSAGES_PER_SECOND = 0x11;
23 
25  const MESSAGES_PER_MINUTE = 0x10;
26 
32  private $_sleeper;
33 
39  private $_timer;
40 
46  private $_start;
47 
53  private $_rate;
54 
62  private $_mode;
63 
69  private $_messages = 0;
70 
79  public function __construct($rate, $mode = self::BYTES_PER_MINUTE, Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null)
80  {
81  $this->_rate = $rate;
82  $this->_mode = $mode;
83  $this->_sleeper = $sleeper;
84  $this->_timer = $timer;
85  }
86 
93  {
94  $time = $this->getTimestamp();
95  if (!isset($this->_start)) {
96  $this->_start = $time;
97  }
98  $duration = $time - $this->_start;
99 
100  switch ($this->_mode) {
101  case self::BYTES_PER_MINUTE :
102  $sleep = $this->_throttleBytesPerMinute($duration);
103  break;
104  case self::MESSAGES_PER_SECOND :
105  $sleep = $this->_throttleMessagesPerSecond($duration);
106  break;
107  case self::MESSAGES_PER_MINUTE :
108  $sleep = $this->_throttleMessagesPerMinute($duration);
109  break;
110  default :
111  $sleep = 0;
112  break;
113  }
114 
115  if ($sleep > 0) {
116  $this->sleep($sleep);
117  }
118  }
119 
125  public function sendPerformed(Swift_Events_SendEvent $evt)
126  {
127  parent::sendPerformed($evt);
129  }
130 
136  public function sleep($seconds)
137  {
138  if (isset($this->_sleeper)) {
139  $this->_sleeper->sleep($seconds);
140  } else {
141  sleep($seconds);
142  }
143  }
144 
150  public function getTimestamp()
151  {
152  if (isset($this->_timer)) {
153  return $this->_timer->getTimestamp();
154  } else {
155  return time();
156  }
157  }
158 
166  private function _throttleBytesPerMinute($timePassed)
167  {
168  $expectedDuration = $this->getBytesOut() / ($this->_rate / 60);
169 
170  return (int) ceil($expectedDuration - $timePassed);
171  }
172 
180  private function _throttleMessagesPerSecond($timePassed)
181  {
182  $expectedDuration = $this->_messages / ($this->_rate);
183 
184  return (int) ceil($expectedDuration - $timePassed);
185  }
186 
194  private function _throttleMessagesPerMinute($timePassed)
195  {
196  $expectedDuration = $this->_messages / ($this->_rate / 60);
197 
198  return (int) ceil($expectedDuration - $timePassed);
199  }
200 }