Passed
Push — main ( b2d943...872826 )
by Daniel
05:35
created

DispatchTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 27
ccs 0
cts 10
cp 0
rs 10
c 1
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A dispatch() 0 20 5
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Mercure;
15
16
use Symfony\Component\Messenger\Envelope;
17
use Symfony\Component\Messenger\Exception\HandlerFailedException;
18
use Symfony\Component\Messenger\MessageBusInterface;
19
20
/**
21
 * @internal
22
 */
23
trait DispatchTrait
24
{
25
    private ?MessageBusInterface $messageBus;
26
27
    /**
28
     * @param object|Envelope $message
29
     */
30
    private function dispatch(object $message): Envelope
31
    {
32
        if (!$this->messageBus instanceof MessageBusInterface) {
33
            throw new \InvalidArgumentException('The message bus is not set.');
34
        }
35
36
        if (!class_exists(HandlerFailedException::class)) {
37
            return $this->messageBus->dispatch($message);
38
        }
39
40
        try {
41
            return $this->messageBus->dispatch($message);
42
        } catch (HandlerFailedException $e) {
43
            // unwrap the exception thrown in handler for Symfony Messenger >= 4.3
44
            while ($e instanceof HandlerFailedException) {
45
                /** @var \Throwable $e */
46
                $e = $e->getPrevious();
47
            }
48
49
            throw $e;
50
        }
51
    }
52
}
53