Passed
Pull Request — master (#2977)
by Han Hui
04:53
created

DispatchTrait::dispatch()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 20
rs 9.6111
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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 ApiPlatform\Core\Bridge\Symfony\Messenger;
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
    /**
26
     * @var MessageBusInterface|null
27
     */
28
    private $messageBus;
29
30
    /**
31
     * @param object|Envelope $message
32
     */
33
    private function dispatch($message)
34
    {
35
        if (!$this->messageBus instanceof MessageBusInterface) {
36
            throw new \InvalidArgumentException('The message bus is not set.');
37
        }
38
39
        if (!class_exists(HandlerFailedException::class)) {
40
            return $this->messageBus->dispatch($message);
41
        }
42
43
        try {
44
            return $this->messageBus->dispatch($message);
45
        } catch (HandlerFailedException $e) {
46
            // unwrap the exception thrown in handler for Symfony Messenger >= 4.3
47
            while ($e instanceof HandlerFailedException) {
48
                /** @var \Throwable $e */
49
                $e = $e->getPrevious();
50
            }
51
52
            throw $e;
53
        }
54
    }
55
}
56