Passed
Push — master ( 905821...42a403 )
by Mr
07:23
created

LazySubscription   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 5
dl 0
loc 55
ccs 0
cts 41
cp 0
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/message-bus project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\MessageBus\Channel\Subscription;
10
11
use Closure;
12
use Daikon\MessageBus\EnvelopeInterface;
13
use Daikon\MessageBus\MessageBusInterface;
14
15
final class LazySubscription implements SubscriptionInterface
16
{
17
    private string $key;
18
19
    private SubscriptionInterface $compositeSubscription;
20
21
    private Closure $factoryCallback;
22
23
    public function __construct(
24
        string $key,
25
        Closure $transport,
26
        Closure $messageHandlers,
27
        Closure $guard = null,
28
        Closure $metadataEnrichers = null
29
    ) {
30
        $this->key = $key;
31
        $this->factoryCallback = fn(): SubscriptionInterface =>
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ':', expecting T_DOUBLE_ARROW on line 31 at column 37
Loading history...
32
            new Subscription(
33
                $this->key,
34
                $transport(),
35
                $messageHandlers(),
36
                $guard,
37
                $metadataEnrichers ? $metadataEnrichers() : null
38
            );
39
    }
40
41
    public function publish(EnvelopeInterface $envelope, MessageBusInterface $messageBus): void
42
    {
43
        if ($subscription = $this->getSubscription()) {
44
            $subscription->publish($envelope, $messageBus);
45
        }
46
    }
47
48
    public function receive(EnvelopeInterface $envelope): void
49
    {
50
        if ($subscription = $this->getSubscription()) {
51
            $subscription->receive($envelope);
52
        }
53
    }
54
55
    public function getKey(): string
56
    {
57
        return $this->key;
58
    }
59
60
    private function getSubscription(): SubscriptionInterface
61
    {
62
        /** @psalm-suppress TypeDoesNotContainType */
63
        if (!isset($this->compositeSubscription)) {
64
            $this->compositeSubscription = call_user_func($this->factoryCallback);
65
            unset($this->factoryCallback);
66
        }
67
        return $this->compositeSubscription;
68
    }
69
}
70