Transports.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\Transport;
  11. use Symfony\Component\Mailer\Envelope;
  12. use Symfony\Component\Mailer\Exception\InvalidArgumentException;
  13. use Symfony\Component\Mailer\Exception\LogicException;
  14. use Symfony\Component\Mailer\SentMessage;
  15. use Symfony\Component\Mime\Message;
  16. use Symfony\Component\Mime\RawMessage;
  17. /**
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. final class Transports implements TransportInterface
  21. {
  22. private $transports;
  23. private $default;
  24. /**
  25. * @param TransportInterface[] $transports
  26. */
  27. public function __construct(iterable $transports)
  28. {
  29. $this->transports = [];
  30. foreach ($transports as $name => $transport) {
  31. if (null === $this->default) {
  32. $this->default = $transport;
  33. }
  34. $this->transports[$name] = $transport;
  35. }
  36. if (!$this->transports) {
  37. throw new LogicException(sprintf('"%s" must have at least one transport configured.', __CLASS__));
  38. }
  39. }
  40. public function send(RawMessage $message, Envelope $envelope = null): ?SentMessage
  41. {
  42. /** @var Message $message */
  43. if (RawMessage::class === \get_class($message) || !$message->getHeaders()->has('X-Transport')) {
  44. return $this->default->send($message, $envelope);
  45. }
  46. $headers = $message->getHeaders();
  47. $transport = $headers->get('X-Transport')->getBody();
  48. $headers->remove('X-Transport');
  49. if (!isset($this->transports[$transport])) {
  50. throw new InvalidArgumentException(sprintf('The "%s" transport does not exist (available transports: "%s").', $transport, implode('", "', array_keys($this->transports))));
  51. }
  52. return $this->transports[$transport]->send($message, $envelope);
  53. }
  54. public function __toString(): string
  55. {
  56. return '['.implode(',', array_keys($this->transports)).']';
  57. }
  58. }