DelayedEnvelope.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mailer;
  11. use Symfony\Component\Mailer\Exception\LogicException;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Mime\Header\Headers;
  14. use Symfony\Component\Mime\Message;
  15. /**
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. *
  18. * @internal
  19. */
  20. final class DelayedEnvelope extends Envelope
  21. {
  22. private $senderSet = false;
  23. private $recipientsSet = false;
  24. private $message;
  25. public function __construct(Message $message)
  26. {
  27. $this->message = $message;
  28. }
  29. public function setSender(Address $sender): void
  30. {
  31. parent::setSender($sender);
  32. $this->senderSet = true;
  33. }
  34. public function getSender(): Address
  35. {
  36. if (!$this->senderSet) {
  37. parent::setSender(self::getSenderFromHeaders($this->message->getHeaders()));
  38. }
  39. return parent::getSender();
  40. }
  41. public function setRecipients(array $recipients): void
  42. {
  43. parent::setRecipients($recipients);
  44. $this->recipientsSet = parent::getRecipients();
  45. }
  46. /**
  47. * @return Address[]
  48. */
  49. public function getRecipients(): array
  50. {
  51. if ($this->recipientsSet) {
  52. return parent::getRecipients();
  53. }
  54. return self::getRecipientsFromHeaders($this->message->getHeaders());
  55. }
  56. private static function getRecipientsFromHeaders(Headers $headers): array
  57. {
  58. $recipients = [];
  59. foreach (['to', 'cc', 'bcc'] as $name) {
  60. foreach ($headers->all($name) as $header) {
  61. foreach ($header->getAddresses() as $address) {
  62. $recipients[] = $address;
  63. }
  64. }
  65. }
  66. return $recipients;
  67. }
  68. private static function getSenderFromHeaders(Headers $headers): Address
  69. {
  70. if ($sender = $headers->get('Sender')) {
  71. return $sender->getAddress();
  72. }
  73. if ($from = $headers->get('From')) {
  74. return $from->getAddresses()[0];
  75. }
  76. if ($return = $headers->get('Return-Path')) {
  77. return $return->getAddress();
  78. }
  79. throw new LogicException('Unable to determine the sender of the message.');
  80. }
  81. }