XOOPS RMCommon Utilities  2.1.8.91RC
 All Classes Namespaces Files Functions Variables
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 
11 //@require 'Swift/Events/SendEvent.php';
12 //@require 'Swift/Plugins/BandwidthMonitorPlugin.php';
13 //@require 'Swift/Plugins/Sleeper.php';
14 //@require 'Swift/Plugins/Timer.php';
15 
25 {
26 
28  const BYTES_PER_MINUTE = 0x01;
29 
31  const MESSAGES_PER_MINUTE = 0x10;
32 
38  private $_sleeper;
39 
45  private $_timer;
46 
52  private $_start;
53 
59  private $_rate;
60 
67  private $_mode;
68 
74  private $_messages = 0;
75 
83  public function __construct($rate, $mode = self::BYTES_PER_MINUTE,
84  Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null)
85  {
86  $this->_rate = $rate;
87  $this->_mode = $mode;
88  $this->_sleeper = $sleeper;
89  $this->_timer = $timer;
90  }
91 
97  {
98  $time = $this->getTimestamp();
99  if (!isset($this->_start))
100  {
101  $this->_start = $time;
102  }
103  $duration = $time - $this->_start;
104 
105  if (self::BYTES_PER_MINUTE == $this->_mode)
106  {
107  $sleep = $this->_throttleBytesPerMinute($duration);
108  }
109  else
110  {
111  $sleep = $this->_throttleMessagesPerMinute($duration);
112  }
113 
114  if ($sleep > 0)
115  {
116  $this->sleep($sleep);
117  }
118  }
119 
124  public function sendPerformed(Swift_Events_SendEvent $evt)
125  {
126  parent::sendPerformed($evt);
128  }
129 
134  public function sleep($seconds)
135  {
136  if (isset($this->_sleeper))
137  {
138  $this->_sleeper->sleep($seconds);
139  }
140  else
141  {
142  sleep($seconds);
143  }
144  }
145 
150  public function getTimestamp()
151  {
152  if (isset($this->_timer))
153  {
154  return $this->_timer->getTimestamp();
155  }
156  else
157  {
158  return time();
159  }
160  }
161 
162  // -- Private methods
163 
170  private function _throttleBytesPerMinute($timePassed)
171  {
172  $expectedDuration = $this->getBytesOut() / ($this->_rate / 60);
173  return (int) ceil($expectedDuration - $timePassed);
174  }
175 
182  private function _throttleMessagesPerMinute($timePassed)
183  {
184  $expectedDuration = $this->_messages / ($this->_rate / 60);
185  return (int) ceil($expectedDuration - $timePassed);
186  }
187 
188 }