MemorySpool.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2011 Fabien Potencier <fabien.potencier@gmail.com>
  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. * Stores Messages in memory.
  11. *
  12. * @author Fabien Potencier
  13. */
  14. class Swift_MemorySpool implements Swift_Spool
  15. {
  16. protected $messages = [];
  17. private $flushRetries = 3;
  18. /**
  19. * Tests if this Transport mechanism has started.
  20. *
  21. * @return bool
  22. */
  23. public function isStarted()
  24. {
  25. return true;
  26. }
  27. /**
  28. * Starts this Transport mechanism.
  29. */
  30. public function start()
  31. {
  32. }
  33. /**
  34. * Stops this Transport mechanism.
  35. */
  36. public function stop()
  37. {
  38. }
  39. /**
  40. * @param int $retries
  41. */
  42. public function setFlushRetries($retries)
  43. {
  44. $this->flushRetries = $retries;
  45. }
  46. /**
  47. * Stores a message in the queue.
  48. *
  49. * @param Swift_Mime_SimpleMessage $message The message to store
  50. *
  51. * @return bool Whether the operation has succeeded
  52. */
  53. public function queueMessage(Swift_Mime_SimpleMessage $message)
  54. {
  55. //clone the message to make sure it is not changed while in the queue
  56. $this->messages[] = clone $message;
  57. return true;
  58. }
  59. /**
  60. * Sends messages using the given transport instance.
  61. *
  62. * @param Swift_Transport $transport A transport instance
  63. * @param string[] $failedRecipients An array of failures by-reference
  64. *
  65. * @return int The number of sent emails
  66. */
  67. public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
  68. {
  69. if (!$this->messages) {
  70. return 0;
  71. }
  72. if (!$transport->isStarted()) {
  73. $transport->start();
  74. }
  75. $count = 0;
  76. $retries = $this->flushRetries;
  77. while ($retries--) {
  78. try {
  79. while ($message = array_pop($this->messages)) {
  80. $count += $transport->send($message, $failedRecipients);
  81. }
  82. } catch (Swift_TransportException $exception) {
  83. if ($retries) {
  84. // re-queue the message at the end of the queue to give a chance
  85. // to the other messages to be sent, in case the failure was due to
  86. // this message and not just the transport failing
  87. array_unshift($this->messages, $message);
  88. // wait half a second before we try again
  89. usleep(500000);
  90. } else {
  91. throw $exception;
  92. }
  93. }
  94. }
  95. return $count;
  96. }
  97. }