Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
66.67% covered (warning)
66.67%
2 / 3
CRAP
92.86% covered (success)
92.86%
13 / 14
RoutableMessageBus
0.00% covered (danger)
0.00%
0 / 1
66.67% covered (warning)
66.67%
2 / 3
7.02
92.86% covered (success)
92.86%
13 / 14
 __construct
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
3 / 3
 dispatch
0.00% covered (danger)
0.00%
0 / 1
4.03
87.50% covered (warning)
87.50%
7 / 8
 getMessageBus
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
3 / 3
1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Messenger;
13
14use Psr\Container\ContainerInterface;
15use Symfony\Component\Messenger\Exception\InvalidArgumentException;
16use Symfony\Component\Messenger\Stamp\BusNameStamp;
17
18/**
19 * Bus of buses that is routable using a BusNameStamp.
20 *
21 * This is useful when passed to Worker: messages received
22 * from the transport can be sent to the correct bus.
23 *
24 * @author Ryan Weaver <ryan@symfonycasts.com>
25 */
26class RoutableMessageBus implements MessageBusInterface
27{
28    private $busLocator;
29    private $fallbackBus;
30
31    public function __construct(ContainerInterface $busLocator, MessageBusInterface $fallbackBus = null)
32    {
33        $this->busLocator = $busLocator;
34        $this->fallbackBus = $fallbackBus;
35    }
36
37    public function dispatch($envelope, array $stamps = []): Envelope
38    {
39        if (!$envelope instanceof Envelope) {
40            throw new InvalidArgumentException('Messages passed to RoutableMessageBus::dispatch() must be inside an Envelope.');
41        }
42
43        /** @var BusNameStamp|null $busNameStamp */
44        $busNameStamp = $envelope->last(BusNameStamp::class);
45
46        if (null === $busNameStamp) {
47            if (null === $this->fallbackBus) {
48                throw new InvalidArgumentException(sprintf('Envelope is missing a BusNameStamp and no fallback message bus is configured on RoutableMessageBus.'));
49            }
50
51            return $this->fallbackBus->dispatch($envelope, $stamps);
52        }
53
54        return $this->getMessageBus($busNameStamp->getBusName())->dispatch($envelope, $stamps);
55    }
56
57    /**
58     * @internal
59     */
60    public function getMessageBus(string $busName): MessageBusInterface
61    {
62        if (!$this->busLocator->has($busName)) {
63            throw new InvalidArgumentException(sprintf('Bus named "%s" does not exist.', $busName));
64        }
65
66        return $this->busLocator->get($busName);
67    }
68}