Transports.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\Notifier\Transport;
  11. use Symfony\Component\Notifier\Exception\InvalidArgumentException;
  12. use Symfony\Component\Notifier\Message\MessageInterface;
  13. /**
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. *
  16. * @experimental in 5.1
  17. */
  18. final class Transports implements TransportInterface
  19. {
  20. private $transports;
  21. private $default;
  22. /**
  23. * @param TransportInterface[] $transports
  24. */
  25. public function __construct(iterable $transports)
  26. {
  27. $this->transports = [];
  28. foreach ($transports as $name => $transport) {
  29. if (null === $this->default) {
  30. $this->default = $transport;
  31. }
  32. $this->transports[$name] = $transport;
  33. }
  34. }
  35. public function __toString(): string
  36. {
  37. return '['.implode(',', array_keys($this->transports)).']';
  38. }
  39. public function supports(MessageInterface $message): bool
  40. {
  41. foreach ($this->transports as $transport) {
  42. if ($transport->supports($message)) {
  43. return true;
  44. }
  45. }
  46. return false;
  47. }
  48. public function send(MessageInterface $message): void
  49. {
  50. if (!$transport = $message->getTransport()) {
  51. $this->default->send($message);
  52. return;
  53. }
  54. if (!isset($this->transports[$transport])) {
  55. throw new InvalidArgumentException(sprintf('The "%s" transport does not exist.', $transport));
  56. }
  57. $this->transports[$transport]->send($message);
  58. }
  59. }