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

DispatchTrait::dispatch()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 20
ccs 0
cts 10
cp 0
crap 30
rs 9.6111
c 1
b 0
f 0
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