SendersLocator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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\Messenger\Transport\Sender;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\Messenger\Envelope;
  13. use Symfony\Component\Messenger\Exception\RuntimeException;
  14. use Symfony\Component\Messenger\Handler\HandlersLocator;
  15. /**
  16. * Maps a message to a list of senders.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class SendersLocator implements SendersLocatorInterface
  21. {
  22. private $sendersMap;
  23. private $sendersLocator;
  24. /**
  25. * @param string[][] $sendersMap An array, keyed by "type", set to an array of sender aliases
  26. * @param ContainerInterface $sendersLocator Locator of senders, keyed by sender alias
  27. */
  28. public function __construct(array $sendersMap, ContainerInterface $sendersLocator)
  29. {
  30. $this->sendersMap = $sendersMap;
  31. $this->sendersLocator = $sendersLocator;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function getSenders(Envelope $envelope): iterable
  37. {
  38. $seen = [];
  39. foreach (HandlersLocator::listTypes($envelope) as $type) {
  40. foreach ($this->sendersMap[$type] ?? [] as $senderAlias) {
  41. if (!\in_array($senderAlias, $seen, true)) {
  42. if (!$this->sendersLocator->has($senderAlias)) {
  43. throw new RuntimeException(sprintf('Invalid senders configuration: sender "%s" is not in the senders locator.', $senderAlias));
  44. }
  45. $seen[] = $senderAlias;
  46. $sender = $this->sendersLocator->get($senderAlias);
  47. yield $senderAlias => $sender;
  48. }
  49. }
  50. }
  51. }
  52. }