FailoverTransport.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * Contains a list of redundant Transports so when one fails, the next is used.
  11. *
  12. * @author Chris Corbyn
  13. */
  14. class Swift_Transport_FailoverTransport extends Swift_Transport_LoadBalancedTransport
  15. {
  16. /**
  17. * Registered transport currently used.
  18. *
  19. * @var Swift_Transport
  20. */
  21. private $_currentTransport;
  22. /**
  23. * Creates a new FailoverTransport.
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Send the given Message.
  31. *
  32. * Recipient/sender data will be retrieved from the Message API.
  33. * The return value is the number of recipients who were accepted for delivery.
  34. *
  35. * @param Swift_Mime_Message $message
  36. * @param string[] $failedRecipients An array of failures by-reference
  37. *
  38. * @return int
  39. */
  40. public function send(Swift_Mime_Message $message, &$failedRecipients = null)
  41. {
  42. $maxTransports = count($this->_transports);
  43. $sent = 0;
  44. for ($i = 0; $i < $maxTransports
  45. && $transport = $this->_getNextTransport(); ++$i)
  46. {
  47. try {
  48. if (!$transport->isStarted()) {
  49. $transport->start();
  50. }
  51. return $transport->send($message, $failedRecipients);
  52. } catch (Swift_TransportException $e) {
  53. $this->_killCurrentTransport();
  54. }
  55. }
  56. if (count($this->_transports) == 0) {
  57. throw new Swift_TransportException(
  58. 'All Transports in FailoverTransport failed, or no Transports available'
  59. );
  60. }
  61. return $sent;
  62. }
  63. protected function _getNextTransport()
  64. {
  65. if (!isset($this->_currentTransport)) {
  66. $this->_currentTransport = parent::_getNextTransport();
  67. }
  68. return $this->_currentTransport;
  69. }
  70. protected function _killCurrentTransport()
  71. {
  72. $this->_currentTransport = null;
  73. parent::_killCurrentTransport();
  74. }
  75. }