LazySubscription::publish()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 2
nc 2
nop 2
crap 6
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 Closure $factoryCallback;
20
21
    private SubscriptionInterface $compositeSubscription;
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(): Subscription =>
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 RedundantPropertyInitializationCheck */
63
        if (!isset($this->compositeSubscription)) {
64
            $this->compositeSubscription = ($this->factoryCallback)();
65
            unset($this->factoryCallback);
66
        }
67
        return $this->compositeSubscription;
68
    }
69
}
70